80

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.

1 Answer 1

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

or

sys.stdout.isatty()
Sign up to request clarification or add additional context in comments.

2 Comments

Notice: this is a test for stdout. To check stdin use stdin accordingly.
To check for stderr, use sys.stderr.isatty() accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.