【问题标题】:How to detect if the console does support ANSI escape codes in Python?如何检测控制台是否支持 Python 中的 ANSI 转义码?
【发布时间】:2011-11-18 17:27:44
【问题描述】:

为了检测控制台是否正确,sys.stderrsys.stdout,我正在做以下测试:

if hasattr(sys.stderr, "isatty") and sys.stderr.isatty():
   if platform.system()=='Windows':
       # win code (ANSI not supported but there are alternatives)
   else:
       # use ANSI escapes
else:
   # no colors, usually this is when you redirect the output to a file

现在,通过 IDE(如 PyCharm)运行此 Python 代码时,问题变得更加复杂。最近 PyCharm 增加了对 ANSI 的支持,但第一次测试失败:它有 isatty 属性,但它被设置为 False

我想修改逻辑,以便正确检测输出是否支持 ANSI 着色。一个要求是,在任何情况下,当输出重定向到文件时,我都不应输出某些内容(对于控制台,这是可以接受的)。

更新

https://gist.github.com/1316877添加了更复杂的ANSI测试脚本

【问题讨论】:

    标签: python console stdout ansi-escape windows-controls


    【解决方案1】:

    Django 用户可以使用django.core.management.color.supports_color 函数。

    if supports_color():
        ...
    

    他们使用的代码是:

    def supports_color():
        """
        Returns True if the running system's terminal supports color, and False
        otherwise.
        """
        plat = sys.platform
        supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
                                                      'ANSICON' in os.environ)
        # isatty is not always implemented, #6223.
        is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
        return supported_platform and is_a_tty
    

    https://github.com/django/django/blob/master/django/core/management/color.py

    【讨论】:

      【解决方案2】:

      我可以告诉你其他人是如何解决这个问题的,但它并不漂亮。如果您以 ncurses 为例(它需要能够在各种不同的终端上运行),您会发现它们使用terminal capabilities database 来存储各种终端及其功能。关键是,即使他们也永远无法自动“检测”这些东西。

      我不知道是否有跨平台 termcap,但可能值得您花时间寻找它。即使它在那里,它也可能没有列出您的终端,您可能必须手动添加它。

      【讨论】:

      • PyCharm 团队报告说,目前无法发现您的代码是在 PyCharm 内部执行的。解决方法是自己添加一个环境变量,但是几乎没用。
      • 这张 PyCharm 票讨论了这个问题——youtrack.jetbrains.net/issue/PY-4853(它引用了这个 SO 讨论,我认为有一些相同的参与者)。它记录了他们添加了PYCHARM_HOSTED=1 可用于检测pycharm的环境变量。
      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多