Checking for interactive shell in a Python script

痴心易碎 提交于 2019-11-26 20:45:50

This is often works well enough

import os, sys
if os.isatty(sys.stdout.fileno()):
    ...

From this link you can use the same way and test if stdin is associated to a terminate(tty), you can do this using os.isatty(), example:

>>> os.isatty(0)
True

N.B: From the same link this will fails when you invoke the command remotely via ssh, the solution given is to test if stdin is associated to a pipe.

If you already have a dependency on matplotlib, or you don't mind introducing one, you can always just call matplotlib.is_interactive()

Pych
if sys.flags.interactive:
    #interactive
else:
    #not interactive 

http://docs.python.org/library/sys.html#sys.flags

I make a cover class for testing.

For example you have :

class SuperInteractiveClass(object):
   def get_data_from_stdin(self):
      '... a lot of code here ...'
   '... and a lot of other function'

I make a second class, just for testing

class TestSuperInteractiveClass(SuperInteractiveClass):
    prepared_data = []
    def add_prepared_data(self,data):
        self.prepared_data.append(data)
    def get_data_from_stdin(self):
          return self.prepared_data.pop(0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!