Shep
Shep

Reputation: 8370

How to check if a file is written to terminal?

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

Answers (2)

nos
nos

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

Fred Foo
Fred Foo

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

Related Questions