Reputation: 8370
Is there some way to check if the output of a python process is being written to file? I'd like to be able to do something like:
if is_writing_to_terminal:
sys.stdout.write('one thing')
else:
sys.stdout.write('another thing')
Upvotes: 3
Views: 437
Reputation: 229158
You can use os.isatty()
to check whether a file descriptor is a terminal:
if os.isatty(sys.stdout.fileno()):
sys.stdout.write('one thing')
else:
sys.stdout.write('another thing')
Upvotes: 4
Reputation: 363627
Use os.isatty
. That expects a file descriptor (fd), which can be obtained with the fileno
member.
>>> from os import isatty
>>> isatty(sys.stdout.fileno())
True
If you want to support arbitrary file-likes (e.g. StringIO
), then you have to check whether the file-like has an associated fd since not all file-likes do:
hasattr(f, "fileno") and isatty(f.fileno())
Upvotes: 2