Determining if stdout for a Python process is redirected

前端 未结 3 1300
难免孤独
难免孤独 2021-02-01 06:27

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 s

相关标签:
3条回答
  • 2021-02-01 06:56
    import sys
    
    if sys.stdout.isatty():
        print "Not redirected"
    else:
        sys.stderr.write("Redirected!\n")
    
    0 讨论(0)
  • 2021-02-01 07:05

    Look at

    os.isatty(fd)  
    

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

    0 讨论(0)
  • 2021-02-01 07:08

    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.

    0 讨论(0)
提交回复
热议问题