Python 模块在 Windows 上为标准输出启用 ANSI 颜色? [英] Python module to enable ANSI colors for stdout on Windows?

查看:27
本文介绍了Python 模块在 Windows 上为标准输出启用 ANSI 颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以在 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.

这篇关于Python 模块在 Windows 上为标准输出启用 ANSI 颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆