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

Rei*_*ica 127 python terminal console

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

$ python foo.py  # user types this on console
Run Code Online (Sandbox Code Playgroud)

要么

$ python foo.py > output.txt # redirection
$ python foo.py | grep ....  # pipe
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*dle 203

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

  • 要在shell中演示,请将`python -c"import sys; print(sys.stdout.isatty())"`(应该写为`True`)与`python -c"import sys; print(sys.stdout.isatty)进行比较())"| grep .`(应该写'False`). (30认同)
  • 当您在终端中但进行重定向时,stderr 可能会转到终端,而 stdout 不会,这会变得很奇怪。 (3认同)