1

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?

ersbygre1
  • 181
  • 6
  • Does this answer your question? [How do I determine if sys.stdin is redirected from a file vs. piped from another process?](https://stackoverflow.com/questions/13442574/how-do-i-determine-if-sys-stdin-is-redirected-from-a-file-vs-piped-from-another) – Brian61354270 Jun 30 '22 at 14:08
  • @y.y I'm not sure what you're trying to say – Brian61354270 Jun 30 '22 at 14:09
  • @Brian After testing the accepted answer in your link (and changing the print statements to print functions for python3), the output was the same: in both cases the output said "terminal", whether I used "> log.txt" or not. So it unfortunately didn't work. – ersbygre1 Jun 30 '22 at 14:11
  • @ersbygre1 Were you checking _stdin_ or _stdout_? The idea is the same for both, but the code in the dupe uses `sys.stdin.fileno()` (i.e. 0). You want `sys.stdout.fileno()` (i.e. 1) – Brian61354270 Jun 30 '22 at 14:12
  • Potential duplicates: [Determining if stdout for a Python process is redirected](https://stackoverflow.com/q/1512457/11082165), and [How do I detect whether sys.stdout is attached to terminal or not?](https://stackoverflow.com/q/1077113/11082165), and [How to recognize whether a script is running on a tty?](https://stackoverflow.com/q/858623/11082165) – Brian61354270 Jun 30 '22 at 14:17

1 Answers1

3

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")
Thickycat
  • 894
  • 6
  • 12