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

爱⌒轻易说出口 提交于 2019-11-26 09:51:36

问题


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?


回答1:


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



回答2:


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.



回答3:


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.




回答4:


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.




回答5:


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

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



回答6:


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



来源:https://stackoverflow.com/questions/12492810/python-how-can-i-make-the-ansi-escape-codes-to-work-also-in-windows

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