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

Time:06-30

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?

CodePudding user response:

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")
  • Related