Checking for interactive shell in a Python script

Question:

I need to determine whether the shell which invoked my Python script was in interactive mode or not. If it was in interactive mode, the program should pipe output to less(1) for easy reading. If not, it should simply print its output to stdout, to allow it to be piped away to a printer, file, or a different pager.

In a shell script, I would have checked if the prompt variable $PS1 was defined, or looked for the -i option among the flags stored in the $- variable.

What is the preferred method for testing interactivity from within Python?

Asked By: jforberg

||

Answers:

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)
Answered By: Oduvan

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.

Answered By: mouad

This is often works well enough

import os, sys
if os.isatty(sys.stdout.fileno()):
    ...
Answered By: John La Rooy
if sys.flags.interactive:
    #interactive
else:
    #not interactive 

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

Answered By: Pych

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

Answered By: schwartrer
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.