如何检测sys.stdout是否已连接到终端? [英] How do I detect whether sys.stdout is attached to terminal or not?

查看:399
本文介绍了如何检测sys.stdout是否已连接到终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

$ 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).

推荐答案

if sys.stdout.isatty():
    # You're running in a real terminal
else:
    # You're being piped or redirected

这篇关于如何检测sys.stdout是否已连接到终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆