24

I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).

Is there a reasonable way to do this in a Python script? So:

$ python my_script.py
Not redirected

and

$ python my_script.py > output.txt  
Redirected!
Alen Paul Varghese
  • 1,278
  • 14
  • 27
Jeffrey Harris
  • 3,480
  • 25
  • 30

3 Answers3

45
import sys

if sys.stdout.isatty():
    print("Not redirected")
else:
    sys.stderr.write("Redirected!\n")
Neuron
  • 5,141
  • 5
  • 38
  • 59
nosklo
  • 217,122
  • 57
  • 293
  • 297
15

Actually, what you want to do here is find out if stdin and stdout are the same thing.

$ cat test.py
import os
print(os.fstat(0) == os.fstat(1))
$ python test.py
True
$ python test.py > f
$ cat f
False
$ 

The longer but more traditional version of the are they the same file test just compares st_ino and st_dev. Typically, on windows these are faked up with a hash of something so that this exact design pattern will work.

Neuron
  • 5,141
  • 5
  • 38
  • 59
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • Since this works on Windows I think it's what I want. Note that this approach *won't* work if I do: $ echo "blah" | python test.py – Jeffrey Harris Oct 04 '09 at 18:49
  • 1
    This tells you if either stdin OR stdout have been redirected. `echo foo | python test.py` will also result in "False" as an output. – CDahn Feb 04 '22 at 21:05
4

Look at

os.isatty(fd)  

(I don't think this works on Windows, however)

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190