This question already has an answer here:
这个问题已经有了答案:
- How to recognize whether a script is running on a tty? 1 answer
- 如何识别脚本是否在tty上运行?1回答
Is there a way to detect whether sys.stdout
is attached to a console terminal or not? For example, I want to be able to detect if foo.py is run via:
是否有办法检测系统。stdout是否连接到控制台终端?例如,我希望能够检测foo。py是通过运行:
$ python foo.py # user types this on console
OR
或
$ python foo.py > output.txt # redirection
$ python foo.py | grep .... # pipe
The reason I ask this question is that I want to make sure that my progressbar display happens only in the former case (real console).
我问这个问题的原因是,我想确保我的progressbar显示只发生在以前的情况(真实的控制台)中。
1 个解决方案
#1
173
if sys.stdout.isatty():
# You're running in a real terminal
else:
# You're being piped or redirected
#1
173
if sys.stdout.isatty():
# You're running in a real terminal
else:
# You're being piped or redirected