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

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


This can be detected using isatty:

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