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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)