Search code examples
pythonterminalansi-colors

output of [31m text instead of color


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?


Solution

  • 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.