如何检测系统。stdout是否连接到终端?(复制)

时间:2022-06-29 00:04:58

This question already has an answer here:

这个问题已经有了答案:

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