How to recognize whether a script is running on a tty?

PythonShell

Python Problem Overview


I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command).

How do I recognize which of these two happen in a Python script?

Example of such behavior in existing program: grep --color=auto highlights matches when running in interactive shell, but doesn't when piped to something else.

Python Solutions


Solution 1 - Python

import os, sys
os.isatty(sys.stdout.fileno())

or

sys.stdout.isatty()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaweł HajdanView Question on Stackoverflow
Solution 1 - PythonjdizzleView Answer on Stackoverflow