Python 如何检测sys.stdout是否连接到终端?

Python 如何检测sys.stdout是否连接到终端?,python,console,terminal,Python,Console,Terminal,是否有办法检测sys.stdout是否连接到控制台终端?例如,我希望能够检测foo.py是否通过以下方式运行: $ python foo.py # user types this on console 或 我问这个问题的原因是我想确保progressbar显示只在前一种情况下出现(real console)。这可以通过以下方式检测: 要在shell中演示这一点,请执行以下操作: python-c“import sys;print(sys.stdout.isatty())”应为True py

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

$ python foo.py  # user types this on console


我问这个问题的原因是我想确保progressbar显示只在前一种情况下出现(real console)。

这可以通过以下方式检测:

要在shell中演示这一点,请执行以下操作:

  • python-c“import sys;print(sys.stdout.isatty())”
    应为True
  • python-c“导入系统;打印(sys.stdout.isatty())”| cat
    应写入False

当你在一个终端中时,这会变得很奇怪,但在stdout没有重定向的情况下,stderr可能会转到一个终端。
$ python foo.py > output.txt # redirection
$ python foo.py | grep ....  # pipe
if sys.stdout.isatty():
    # You're running in a real terminal
else:
    # You're being piped or redirected