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中演示这一点,请执行以下操作:
应为Truepython-c“import sys;print(sys.stdout.isatty())”
应写入Falsepython-c“导入系统;打印(sys.stdout.isatty())”| cat
$ 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