如何使用 Python 在 Windows 命令提示符下使用颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1328643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:01:57  来源:igfitidea点击:

How do I use colour with Windows command prompt using Python?

pythonwindowscommand-promptwaf

提问by Nick Bolton

I'm trying to patch a waf issue, where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me in right direction?

我正在尝试修补一个waf 问题,其中 Windows 命令提示符输出没有按预期着色。我试图弄清楚如何实际实施此补丁,但我无法找到足够的资源 - 有人能指出我正确的方向吗?

Update 1

更新 1

Please don't suggest anything that requires Cygwin.

请不要建议任何需要 Cygwin 的东西。

回答by luc

It is possible thanks to ctypes and SetConsoleTextAttribute

这要归功于 ctypes 和SetConsoleTextAttribute

Here is an example

这是一个例子

from ctypes import *
STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)
windll.Kernel32.GetStdHandle.restype = c_ulong
std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)
for color in xrange(16):
    windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, color)
    print "hello"

回答by Alex Martelli

If you're keen on using normal cmd.exe consoles for the Python interactive interpreter, see this recipe. If you're OK with using special windows simulating a console, for example because you also need more advanced curses functionality anyway, then @TheLobster's suggestion of wcurses is just fine.

如果您热衷于将普通 cmd.exe 控制台用于 Python 交互式解释器,请参阅此秘籍。如果您可以使用模拟控制台的特殊窗口,例如因为无论如何您还需要更高级的 curses 功能,那么@TheLobster 对 wcurses 的建议就很好。