1

From this question I learned how to color Python. I figured out all the color codes, don't worry.
Anyway, the answer that worked for me was the ctypes one by orip. It's a bit tiresome to have to have to type ctypes.windll.kernel32.SetConsoleTextAttribute(handle, AQUA) every time I want to color text. Is there a way to convert it into a function? I'm not sure how to send variables through functions, and not sure how to implement them, even if I did.
Thanks in advance! -ghostmancer All that matters for me is that it works for me - I'm not planning to give my script away. My colors:

BLACK    = 0x0000
BLUE    = 0x0001
GREEN    = 0x0002
RED    = 0x0004
PURPLE    = 0x0005
YELLOW    = 0x0006
WHITE    = 0x0007
GRAY    = 0x0008
GREY    = 0x0008
AQUA    = 0x0009 #Very Blue
Community
  • 1
  • 1
Andrey
  • 849
  • 5
  • 17
  • 28

5 Answers5

3

ummm... if i understand right ...

def a_func(handle,color):
   ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

a_func(handle,AQUA)

or even better

colorFunc = ctypes.windll.kernel32.SetConsoleTextAttribute
colorFunc(handle,AQUA)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 1
    Or even better-er: `from ctypes.windll.kernel32 import SetConsoleTextAttribute as set_color`. If anyone actually cares for portability outside of Windows, then option #1 is best, as it provides an abstraction that you can proliferate in your program and only need to change one location inside the abstracted function later (e.g. adding GNU+Linux support). – code_dredd May 08 '19 at 19:22
2

no need to create a new function with def or lambda, just assign the function with a long name to a shorter name, e.g:

textcolor = ctypes.windll.kernel32.SetConsoleTextAttribute
textcolor(handle, color)
Kimvais
  • 38,306
  • 16
  • 108
  • 142
1

One way is

def textcolor(handle, color):
    ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

which you call like so:

textcolor(handle, AQUA)
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
0

You can use:

f=lambda handle,color:ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

and, call f(<Actual handle object>, <color>) wherever you want. e.g. f(handle, AQUA) would be the required call

GodMan
  • 2,561
  • 2
  • 24
  • 40
0

Because I see the variable 'handle' everywhere without being defined and for anyone who wonders, here is a way to get it, as far as stdout is concerned, so that we can used it with ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color):

STD_OUTPUT_HANDLE = -11
handle = ctypes.windll.kernel32.GetStdHandle(-STD_OUTPUT_HANDLE)
Apostolos
  • 3,115
  • 25
  • 28