color text in windows 10 cmd in python

You can use the ctypes module in Python to color text in Windows 10 cmd. Here is an example code snippet that demonstrates how to print colored text in the command prompt:

main.py
import ctypes

# Colors
FOREGROUND_RED = 0x0004
FOREGROUND_GREEN = 0x0002
FOREGROUND_BLUE = 0x0001
FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN
FOREGROUND_CYAN = FOREGROUND_GREEN | FOREGROUND_BLUE
FOREGROUND_MAGENTA = FOREGROUND_RED | FOREGROUND_BLUE
FOREGROUND_WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
# Standard output handler
STD_OUTPUT_HANDLE = -11

# Get handle to the standard output
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

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

def reset_color():
    set_color(FOREGROUND_WHITE)

# Print colored text
set_color(FOREGROUND_YELLOW)
print("Yellow colored text")
reset_color()
print("Normal text")
738 chars
28 lines

In this code snippet, we define different colors using hexadecimal values and then use the SetConsoleTextAttribute function from kernel32 DLL to set the text color. Don't forget to reset the color after you're done with colored text to avoid applying colors to subsequent text.

related categories

gistlibby LogSnag