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

不想你离开。 提交于 2019-11-27 01:59:35
pr0gg3d

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

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.

If you are on Win 10 (with native ANSI support in cmd) there seems to be a bug which was marked as resolvedin Python 3.7 (though it doesn't look it was actually fixed).

One workaround is to add subprocess.call('', shell=True) before printing.

nmenezes

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.

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

start = "\033[;1;31m"
end = "\033[;0;0m"

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("\033[48;2;255;140;60m ORANGE BACKGROUND \033[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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!