为了检测控制台是否正确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
现在,通过 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
关于python - 如何检测控制台是否支持 Python 中的 ANSI 转义码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7445658/