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

标签 python console stdout ansi-escape windows-controls

为了检测控制台是否正确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

关于python - 如何检测控制台是否支持 Python 中的 ANSI 转义码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7445658/

相关文章:

python - PyQt4:为什么我们需要在调用 super() 时传递类名

python - 带有排序列表的 Pandas 列的名字

javascript - node.js child_process spawn stdout 降低 highWaterMark

基于Python文本的游戏显示

c - 向子进程发送信号时出现问题

c++ - 以十六进制或十进制打印到 stdout,一个 std::string 作为字节序列

go - 从 Go 中的 StdoutPipe() 读取卡住

python - 循环互相关python

python - 如何将简单的网络数据帧更改为相关表?

c++ - 如何在 Windows 上正确地将拉丁字符打印到 C++ 控制台?