【问题标题】:How to detect a pseudo-console in Python in order to activate coloring?如何在 Python 中检测伪控制台以激活着色?
【发布时间】:2017-02-15 10:27:32
【问题描述】:

支持控制台着色的应用程序通常的规则是在当前控制台是 TTY 时激活它。

这种方法在持续集成服务器(如 Jenkins、Travis 等)上会失效,因为它们没有为其伪控制台打开 TTY。

我想知道是否可以区分这两种情况:

  • mycommand 在 Jenkins 下运行 - 我们要启用着色
  • mycommand >> output.log -- 我们不想在日志文件中出现 ANSI 转义。

我的旧 ANSI 检测代码:

import sys
import os

if (hasattr(sys.stderr, "isatty") and sys.stderr.isatty()) or \
    ('TERM' in os.environ.keys() and os.environ['TERM'] in ['linux']) or \
    ('PYCHARM_HOSTED' in os.environ.keys()):
    coloring = True

我可以改进它以解决这个问题吗?

【问题讨论】:

    标签: python jenkins travis-ci tty ansi-escape


    【解决方案1】:

    由于您已经在使用环境变量PYCHARM_HOSTED,我建议您在 CI 环境中使用类似的东西。你特别提到了 Jenkins 和 Travis。这两个系统都设置了可以使用的环境变量。一些可能性是......

    Jenkins 环境变量:

    JENKINS_URL  Set to the URL of the Jenkins master that's running the build.
    BUILD_URL    The URL where the results of this build can be found.
    BUILD_TAG    String of jenkins-${JOB_NAME}-${BUILD_NUMBER}.
    

    (Source)

    Travis 环境变量:

    CI=true
    TRAVIS=true
    CONTINUOUS_INTEGRATION=true
    

    (Source)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多