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

Posted on

Question :

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

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).

Answer #1:

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

Leave a Reply

Your email address will not be published. Required fields are marked *