Python 模块在 Windows 上为标准输出启用 ANSI 颜色?
我正在寻找一个可以在 Windows 下添加 ANSI 支持的 Python 模块。
这意味着导入模块后,如果输出 ANSI 转义字符串,它们将相应地出现。
I am looking for a Python module that would add ANSI support under Windows.
This means that after importing the module, if you output ANSI escaped strings, they will appear accordingly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您最好的选择可能是使用 colorama 模块。
事实上,我认为 Windows 控制台本身并不支持 ANSI 颜色。 colorama 通过拦截 ANSI 序列并执行适当的 Windows 颜色更改调用来解决此困难。这样,您的代码就可以非常方便地移植,因为它可以在 Windows 和 ANSI 兼容终端上以相同的方式打印颜色。
Your best bet is probably to use the colorama module.
In fact, I believe that the Windows console does not support ANSI colors natively. colorama solves this difficulty by intercepting ANSI sequences and performing the appropriate Windows color change calls. This way, your code can be quite portable, as it can print colors in the same way both on Windows and in ANSI-compliant terminals.
有两个 python 模块可以执行此操作
colorama
和tendo.ansiterm
模块,最初是为waf
。通过初步测试表明
colorama
更加成熟,即使它需要两行代码而不是一行。现在,两者都可以正常工作,但如果您尝试仅重定向 stderr 或 stdout 之一,ansiterm 会将 ANSI 代码输出到屏幕并重定向输出。
我不确定,但我怀疑正确的行为是当输出 si 不是 tty 时去除 ANSI 代码,您不想在日志文件中看到 ANSI 转义。
There are two python modules that are able to do this
colorama
andtendo.ansiterm
module, which was originally written forwaf
.By initial tests indicate that
colorama
is more mature, even if it requires two lines of code instead of one.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.
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.
您还可以使用 colorful ,它使用 colorama 来实现可移植性。
You can also use colorful which use colorama for portability.