输出[31m文本而不是颜色

12 python terminal ansi-colors

我正在尝试使用colorama打印彩色文本,但是当我编译exe并运行以下时...

from colorama import Fore, Back, Style
print(Fore.RED + 'text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
I get output of::
Run Code Online (Sandbox Code Playgroud)

输出:

[31mtext
[0m
back to normal now
Run Code Online (Sandbox Code Playgroud)

在编译为pyinstaller exe时是否可以打印颜色,或者这根本不可能?

Ser*_*kov 8

在Windows上,您必须初始化Colorama colorama.init()(参见第二行):

from colorama import Fore, Back, Style
colorama.init()
print(Fore.RED + 'text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
Run Code Online (Sandbox Code Playgroud)

我在测试此代码cmdPowerShell它产生预期的彩色输出.

来自Colorama文档:

在Windows中,调用init()将过滤ANSI转义序列的任何文本发送到stdoutstderr,并具有同等Win32调用替换它们.

在其他平台上,调用init()无效(除非您请求其他可选功能;请参阅下面的"Init Keyword Args").通过设计,这允许应用程序init()在所有平台上无条件地调用,之后ANSI输出应该正常工作.