Checking for interactive shell in a Python script

jforberg picture jforberg · May 24, 2011 · Viewed 10.6k times · Source

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?

Answer

John La Rooy picture John La Rooy · May 24, 2011

This is often works well enough

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