How do I detect whether sys.stdout is attached to terminal or not?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Question
00:41 Accepted answer (Score 270)
01:10 Thank you
--
Full question
https://stackoverflow.com/questions/1077...
Accepted answer links:
[isatty]: https://docs.python.org/3/library/io.htm...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #console #terminal
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Question
00:41 Accepted answer (Score 270)
01:10 Thank you
--
Full question
https://stackoverflow.com/questions/1077...
Accepted answer links:
[isatty]: https://docs.python.org/3/library/io.htm...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #console #terminal
#avk47
ACCEPTED ANSWER
Score 295
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 Truepython -c "import sys; print(sys.stdout.isatty())" | catshould write False