Python: How can I make the ANSI escape codes to work also in Windows?
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 os
if 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).
If you are on Win 10 (with native ANSI support in cmd) there seems to be a bug which was marked as resolved in Python 3.7 (though it doesn't look it was actually fixed).
One workaround is to add subprocess.call('', shell=True)
before printing.
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"])
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