Skip to content
Advertisement

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 = "33[1;31m"
end = "33[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?

Advertisement

Answer

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": "33[95m",
    "BLUE": "33[94m",
    "GREEN": "33[92m",
    "RED": "33[91m",
    "ENDC": "33[0m",
}

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