174

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

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

1 Answers1

276

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
Asclepius
  • 57,944
  • 17
  • 167
  • 143
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 3
    It gets weird when you are in a terminal but doing redirections stderr could be going to a terminal while stdout not. – arhuaco Jul 21 '20 at 02:50
  • 1
    @arhuaco - that's where `sys.stderr.isatty()` comes in -- or even `sys.stdin.isatty()` for that matter. – shalomb Apr 08 '23 at 20:54