Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is written to terminal?

Tags:

python

unix

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')
like image 951
Shep Avatar asked Nov 30 '25 02:11

Shep


2 Answers

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')
like image 123
nos Avatar answered Dec 02 '25 16:12

nos


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())
like image 40
Fred Foo Avatar answered Dec 02 '25 16:12

Fred Foo