Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 733
Nick Bolton Avatar asked Aug 25 '09 14:08

Nick Bolton


2 Answers

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"
like image 61
luc Avatar answered Oct 01 '22 21:10

luc


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.

like image 36
Alex Martelli Avatar answered Oct 01 '22 20:10

Alex Martelli