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

2

10

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?

Update 1

Please don't suggest anything that requires Cygwin.

Kith answered 25/8, 2009 at 14:26 Comment(0)
O
21

It is possible thanks to ctypes and 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"
Oared answered 25/8, 2009 at 15:17 Comment(2)
A quick note for other people trying this--it won't work in IDLE, use python.exe or run it as a script in cmd.exeAbsonant
I would encourage the more modern searcher to look at how this is done by iPython, which does things in a generally very smart and portable way.Balcer
S
3

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.

Stirling answered 25/8, 2009 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.