【问题标题】:How do I detect whether sys.stdout is attached to terminal or not? [duplicate]如何检测 sys.stdout 是否连接到终端? [复制]
【发布时间】:2010-11-07 19:21:24
【问题描述】:

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

$ python foo.py  # user types this on console

$ python foo.py > output.txt # redirection
$ python foo.py | grep ....  # pipe

我问这个问题的原因是我想确保我的进度条显示只发生在前一种情况下(真正的控制台)。

【问题讨论】:

    标签: python console terminal


    【解决方案1】:

    这可以使用isatty检测到:

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

    在 shell 中演示:

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

    【讨论】:

    • 当您在终端中时会变得很奇怪,但是执行重定向 stderr 可能会进入终端,而 stdout 则不会。
    猜你喜欢
    • 2011-09-12
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2013-06-22
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多