The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 How Do I Detect Whether Sys.Stdout Is Attached To Terminal Or Not?
00:31 Accepted Answer Score 295
00:53 Thank you

--

Full question
https://stackoverflow.com/questions/1077...

--

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 True
  • python -c "import sys; print(sys.stdout.isatty())" | cat should write False