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

If I run this in python under linux it works:

start = "\033[1;31m"
end = "\033[0;0m"
print "File is: " + start + "<placeholder>" + end

But if I run it in Windows it doesn't work, how can I make the ANSI escape codes work also on Windows?


Solution 1:

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

import os
os.system("")  # enables ansi escape characters in terminal

COLOR = {
    "HEADER": "\033[95m",
    "BLUE": "\033[94m",
    "GREEN": "\033[92m",
    "RED": "\033[91m",
    "ENDC": "\033[0m",
}

print(COLOR["GREEN"], "Testing Green!!", COLOR["ENDC"])

Solution 2:

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 colorama
colorama.init()
start = "\033[1;31m"
end = "\033[0;0m"
print "File is: " + start + "<placeholder>" + end