0

Python 3.7, on Windows print does not work as expected for ANSI color codes until shell=True once in subprocess.call().

In the below links it appears to imply that the ANSI color codes should work using the "print" command out of the box.

How to print colour/color in python? Print in terminal with colors using Python?

the second one mentions VT100 emulation... not sure what exactly that means. I am able to write a batch file that outputs the color fine so I would think (naively) that it should work the same way in Python.

However I am not able to use the ANSI color codes as it seems that the ESC character is being "commented out"(?) because for instance when I

print(u"\u001b[31mHelloWorld")

I am not able to see the colored output, as the ESC character seems to be necessary in Windows and prints in the python shell as "[?]" (a box with a question mark)

Is there something I am missing here?

1 Answers1

3

I found myself an answer. As often happens I just did not look far enough.

the Colorama module can be installed with

py -m pip install colorama

and comes with a method definition at the root of the module called init

colorama.init()

This is a cross platform function in that it is only useful on windows (it saves the active Terminal state for reversal and writes the Terminal to preprocess ANSI codes), it does nothing for other operating systems.

I am thinking about implementing an even more lightweight solution using ctypes and setting the Interpret flags on the active terminal myself.

If you are interested in more information, see here:

https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences

Output Sequences The following terminal sequences are intercepted by the console host when written into the output stream, if the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag is set on the screen buffer handle using the SetConsoleMode flag. Note that the DISABLE_NEWLINE_AUTO_RETURN flag may also be useful in emulating the cursor positioning and scrolling behavior of other terminal emulators in relation to characters written to the final column in any row.

Emphasis mine.