如何检测sys.stdout是否连接到终端?
有没有办法判断 sys.stdout
是否连接到控制台终端?比如,我想知道运行 foo.py 是通过:
$ python foo.py # user types this on console
还是通过
$ python foo.py > output.txt # redirection
$ python foo.py | grep .... # pipe
我问这个问题的原因是,我想确保我的进度条显示只在第一种情况下(真实的控制台)出现。
1 个回答
291
可以通过使用 isatty
来检测这个情况:
if sys.stdout.isatty():
# You're running in a real terminal
else:
# You're being piped or redirected
在命令行中演示这个:
python -c "import sys; print(sys.stdout.isatty())"
这条命令应该输出 Truepython -c "import sys; print(sys.stdout.isatty())" | cat
这条命令应该输出 False