ersbygre1
ersbygre1

Reputation: 181

How to check whether print() prints to terminal or file?

Is there a way in Python 3 to check whether the following command

print('Hello')

prints to the terminal by using

python3 example.py

or prints to the file by using

python3 example.py > log.txt

...? In particular, is there a way to print different things depending on whether I use > log.txt or not?

Upvotes: 1

Views: 79

Answers (1)

Terminologist
Terminologist

Reputation: 983

I think you're looking for:

writing_to_tty = sys.stdout.isatty()

So...

if sys.stdout.isatty():
    print("I'm sending this to the screen")
else:
    print("I'm sending this through a pipeline or to a file")

Upvotes: 3

Related Questions