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

Question:

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?

Asked By: Eduard Florinescu

||

Answers:

You could take a look at https://github.com/kennethreitz/clint

From the readme:

>>> from clint.textui import colored, puts

>>> puts(colored.red('red text'))
red text

# It's red in Windows, OSX, and Linux alike.
Answered By: mfussenegger

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 = "33[1;31m"
end = "33[0;0m"
print "File is: " + start + "<placeholder>" + end
Answered By: pr0gg3d

I wrote a simple module, available at: http://pypi.python.org/pypi/colorconsole

It works with Windows, Mac OS X and Linux. It uses ANSI for Linux and Mac, but native calls to console functions on Windows. You have colors, cursor positioning and keyboard input. It is not a replacement for curses, but can be very useful if you need to use in simple scripts or ASCII games.

The docs can be found here: http://code.google.com/p/colorconsole/wiki/PageName

PS: This is the same answer for Print in terminal with colors using Python?, but I didn’t know how to link to a reply.

Answered By: nmenezes

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.

Answered By: Dan M.

Try adding a semi-colon here 33[;, I get undesirable effects without that semi-colon.

start = "33[;1;31m"
end = "33[;0;0m"
Answered By: Oliver Burt

Sending the ANSI escape sequences should work, according to thousands of fine answers on the internet, but one obscure detail took me two half days to stumble upon. The trick is that a certain registry key must be set. I’m using (just for today) Windows 10 Enterprise, version 1709, build 16299.

In HKEY_CURRENT_USER, under Console, right between TrimLeadingZeros and WindowAlpha there should be VirtualTerminalLevel. If it doesn’t exist, go ahead and create it. It’s a REG_DWORD. Set its value to 1. Open a new terminal, run Python, and have a bit o’ fun.

print("33[48;2;255;140;60m ORANGE BACKGROUND 33[48;2;0;0;0m")

See https://github.com/ytdl-org/youtube-dl/issues/15758 to read stuff by people who know more than I do about this.

Now if I could remember why I wanted to colorize my Python program’s output…

Answered By: DarenW

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).

Answered By: Ubuesque

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"])
Answered By: Gary Vernon Grubb

You can just do this:

import os
os.system("")

This works for me. Command prompt does support color by default.

Answered By: YJiqdAdwTifMxGR
import os
os.system("")

COR = {
    "HEADER": "33[95m",
    "BLUE": "33[94m",
    "GREEN": "33[92m",
    "RED": "33[91m",
    "ENDC": "33[0m",
}

print(COR["RED"]+"Testing Green!!"+COR["ENDC"])

Here is a bit simpler code I have used.

import os
os.system("color") # Alternative - os.system("")

TCOLOR = "33[31;3m"
ENDC = "33[m"
print (TCOLOR + "Make yourself happy" + ENDC)
Answered By: darwinperez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.