python - 如何检测 Python 中的伪控制台以激活着色?

标签 python jenkins travis-ci tty ansi-escape

支持控制台着色的应用程序的通常规则是在当前控制台为 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

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

最佳答案

由于您已经在使用环境变量 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 )

关于python - 如何检测 Python 中的伪控制台以激活着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246713/

相关文章:

python - 在 Travis CI 中缓存从源构建的依赖项有多安全

python - 在 raw_input 中输入 float 、整数或方程来定义变量

python - 具有不同帧速率的子图的 ArtistAnimation

jenkins - job-dsl-core jar 版本更新至 1.44 & githubPullRequest 关闭不起作用

c# - 未找到 Jenkins NUnit 报告文件

mysql - 特拉维斯 : how to run tests against different MySQL backends?

c++ - 在 Travis 服务器上使用 Buck 构建

python - 在 Python 中使用参数调用对象的方法

python - 规范化 json 列并与数据帧的其余部分连接

android - 离线运行检查(来自 Jenkins)Android Studio 1.1 vs 1.5