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

发布于 2024-12-19 16:50:39 字数 93 浏览 3 评论 0原文

我正在寻找一个可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一刻暧昧 2024-12-26 16:50:39

您最好的选择可能是使用 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.

音栖息无 2024-12-26 16:50:39

有两个 python 模块可以执行此操作 coloramatendo.ansiterm 模块,最初是为 waf

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

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

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

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

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

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

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"\033[33mYellow Submarine"
sys.stderr.write"\033[31mred, red , wine!"

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.

删除→记忆 2024-12-26 16:50:39

您还可以使用 colorful ,它使用 colorama 来实现可移植性。

You can also use colorful which use colorama for portability.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文