Fix Python – How do I detect whether sys.stdout is attached to terminal or not? [duplicate]

Question

Asked By – Sridhar Ratnakumar

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 foo.py is run via:

$ python foo.py  # user types this on console

OR

$ python foo.py > output.txt # redirection
$ python foo.py | 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).

Now we will see solution for issue: How do I detect whether sys.stdout is attached to terminal or not? [duplicate]


Answer

This can be detected using isatty:

if sys.stdout.isatty():
    # You're running in a real terminal
else:
    # 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

This question is answered By – RichieHindle

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0