繁体   English   中英

如何检测控制台是否支持Python中的ANSI转义码?

[英]How to detect if the console does support ANSI escape codes in Python?

为了检测控制台,正确的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测试脚本

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

我可以告诉你其他人是如何解决这个问题的,但它并不漂亮。 如果你以ncurses为例(它需要能够在各种不同的终端上运行),你会看到他们使用终端功能数据库来存储各种终端及其功能。 关键是,即使他们从未能够自动“检测”这些事情。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM