output of [31m text instead of color

a 夏天 提交于 2020-07-06 07:43:24

问题


I am trying to print coloured text with colorama but when I compile an exe and run following...

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::

Output:

[31mtext
[0m
back to normal now

Is it possible to print colors when compiling to pyinstaller exe or is this simply not possible?


回答1:


On Windows, you have to initialize Colorama with colorama.init() (see the second line):

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')

I have tested this code in cmd and PowerShell and it produces the expected colored output.

From Colorama docs:

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

On other platforms, calling init() has no effect (unless you request other optional functionality; see “Init Keyword Args”, below). By design, this permits applications to call init() unconditionally on all platforms, after which ANSI output should just work.




回答2:


cmd.exe of Windows doesn't support ANSI escape sequences.

This topic on superuser might helps if you want these be intepreted by cmd.exe natively http://superuser.com/questions/413073/windows-console-with-ansi-colors-handling/

So pure crayons might not works under cmd.exe of Windows.

However according to the documentation of colorama

This has the upshot of providing a simple cross-platform API for printing colored terminal text from Python, and has the happy side-effect that existing applications or libraries which use ANSI sequences to produce colored output on Linux or Macs can now also work on Windows, simply by calling colorama.init().

Try using ConEmu. You might be able to do it



来源:https://stackoverflow.com/questions/47432418/output-of-31m-text-instead-of-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!