Python: How can I make the ANSI escape codes to work also in Windows? Python: How can I make the ANSI escape codes to work also in Windows? windows windows

Python: How can I make the ANSI escape codes to work also in Windows?


For windows, calling os.system("color") makes the ANSI escape sequence get processed correctly:

import osos.system("color")COLOR = {    "HEADER": "\033[95m",    "BLUE": "\033[94m",    "GREEN": "\033[92m",    "RED": "\033[91m",    "ENDC": "\033[0m",}print(COLOR["GREEN"], "Testing Green!!", COLOR["ENDC"])


You could check Python module to enable ANSI colors for stdout on Windows? to see if it's useful.

The colorama module seems to be cross-platform.

You install colorama:

pip install colorama

Then:

import coloramacolorama.init()start = "\033[1;31m"end = "\033[0;0m"print "File is: " + start + "<placeholder>" + end


Here is the solution I have long sought. Simply use the ctypes module, from the standard library. It is installed by default with Python 3.x, only on Windows. So check if the OS is Windows before to use it (with platform.system, for example).

import osif os.name == 'nt': # Only if we are running on Windows    from ctypes import windll    k = windll.kernel32    k.SetConsoleMode(k.GetStdHandle(-11), 7)

After you have done that, you can use ASCII special characters (like \x1b[31m, for red color) as if you were on a Unix operating system :

message = "ERROR"print(f"\x1b[31m{message}\x1b[0m")

I like this solution because it does not need to install a module (like colorama or termcolor).