[英]How to detect if the console does support ANSI escape codes in Python?
In order to detect if console, correctly sys.stderr
or sys.stdout
, I was doing the following test: 为了检测控制台,正确的
sys.stderr
或sys.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
Now the problem became more complex while running this Python code via an IDE (like PyCharm). 现在,通过IDE(如PyCharm)运行此Python代码时,问题变得更加复杂。 Recently PyCharm added support for ANSI, but the first test fails: it has the
isatty
attribute but it is set to False
. 最近PyCharm添加了对ANSI的支持,但第一次测试失败:它具有
isatty
属性但设置为False
。
I want to modify the logic so it will properly detect if the output supports ANSI coloring. 我想修改逻辑,以便正确检测输出是否支持ANSI着色。 One requirement is that under no circumstance I should output something out when the output is redirected to a file (for console it would be acceptable).
一个要求是在任何情况下我都不应该在输出重定向到文件时输出一些东西(对于控制台,它是可以接受的)。
Added more complex ANSI test script at https://gist.github.com/1316877 通过https://gist.github.com/1316877添加了更复杂的ANSI测试脚本
Django users can use django.core.management.color.supports_color
function. Django用户可以使用
django.core.management.color.supports_color
函数。
if supports_color():
...
The code they use is: 他们使用的代码是:
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
See https://github.com/django/django/blob/master/django/core/management/color.py 请参阅https://github.com/django/django/blob/master/django/core/management/color.py
I can tell you how others have solved this problem, but it's not pretty. 我可以告诉你其他人是如何解决这个问题的,但它并不漂亮。 If you look at ncurses as an example (which needs to be able to run on all kinds of different terminals), you'll see that they use a terminal capabilities database to store every kind of terminal and its capabilities.
如果你以ncurses为例(它需要能够在各种不同的终端上运行),你会看到他们使用终端功能数据库来存储各种终端及其功能。 The point being, even they were never able to automatically "detect" these things.
关键是,即使他们从未能够自动“检测”这些事情。
I don't know if there's a cross-platform termcap, but it's probably worth your time to look for it. 我不知道是否有跨平台的termcap,但它可能值得您花时间去寻找它。 Even if it's out there though, it may not have your terminal listed and you may have to manually add it.
即使它在那里,它可能没有列出您的终端,您可能必须手动添加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.