How do I detect whether sys.stdout is attached to terminal or not?


Is there a way to detect whether sys.stdout is attached to a console terminal or not? For example, I want to be able to detect if is run via:

$ python  # user types this on console


$ python > output.txt # redirection
$ python | grep ....  # pipe

The reason I ask this question is that I want to make sure that my progressbar display happens only in the former case (real console).

Asked By: Sridhar Ratnakumar



This can be detected using isatty:

if sys.stdout.isatty():
    # You're running in a real terminal
    # You're being piped or redirected

To demonstrate this in a shell:

  • python -c "import sys; print(sys.stdout.isatty())" should write True
  • python -c "import sys; print(sys.stdout.isatty())" | cat should write False
Answered By: RichieHindle
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.