Python 模块在 Windows 上为标准输出启用 ANSI 颜色?

2022-01-11 00:00:00 python console terminal ansi-escape

问题描述

我正在寻找可以在 Windows 下添加 ANSI 支持的 Python 模块.

I am looking for a Python module that would add ANSI support under Windows.

这意味着导入模块后,如果你输出ANSI转义字符串,它们会相应出现.

This means that after importing the module, if you output ANSI escaped strings, they will appear accordingly.


解决方案

有两个 python 模块可以做到这一点 coloramatendo.ansiterm 模块,最初是为 编写的waf.

There are two python modules that are able to do this colorama and tendo.ansiterm module, which was originally written for waf.

初步测试表明 colorama 更加成熟,即使它需要两行代码而不是一行.

By initial tests indicate that colorama is more mature, even if it requires two lines of code instead of one.

import sys
try:
   import colorama
   colorama.init()
except:
   try:
       import tendo.ansiterm
   except:
       pass

sys.stdout.write"33[33mYellow Submarine"
sys.stderr.write"33[31mred, red , wine!"

现在,两者都将正常工作,但如果您尝试仅重定向 stderr 或 stdout 之一,ansiterm 会将 ANSI 代码输出到屏幕并重定向输出.

Now, both will work normally but if you try to redirect only one of the stderr or stdout, ansiterm will output ANSI codes to screen and redirected output.

我不确定,但我怀疑正确的行为是在输出 si 不是 tty 时去除 ANSI 代码,您不想在日志文件中看到 ANSI 转义.

I'm not sure but I suspect that the correct behavior is to strip ANSI codes when the output si not a tty, you don't want to see ANSI escapes in log files.

相关文章