output of [31m text instead of color

Question:

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?

Asked By: user8900239

||

Answers:

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

Answered By: bigbounty

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

from colorama import init, Fore, Back, Style
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.

Answered By: SergiyKolesnikov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.