如何检测sys.stdout是否附加到终端?

时间:2009-07-02 23:01:07

标签: python console terminal

有没有办法检测sys.stdout是否附加到控制台终端?例如,我希望能够检测foo.py是否通过以下方式运行:

$ python foo.py  # user types this on console

OR

$ python foo.py > output.txt # redirection
$ python foo.py | grep ....  # pipe

我问这个问题的原因是我想确保我的进度条显示只发生在前一种情况下(真正的控制台)。

1 个答案:

答案 0 :(得分:190)

if sys.stdout.isatty():
    # You're running in a real terminal
else:
    # You're being piped or redirected