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

查看:28
本文介绍了如何检测 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

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

推荐答案

这可以使用 isatty:

This can be detected using isatty:

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

在 shell 中演示这一点:

To demonstrate this in a shell:

  • python -c "import sys;print(sys.stdout.isatty())" 应该写为 True
  • python -c "import sys;打印(sys.stdout.isatty())";|cat 应该写 False
  • python -c "import sys; print(sys.stdout.isatty())" should write True
  • python -c "import sys; print(sys.stdout.isatty())" | cat should write False

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

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