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')
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')
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With