Skip to content

Instantly share code, notes, and snippets.

@Willy-JL
Last active July 2, 2021 21:56
Show Gist options
  • Save Willy-JL/39ceae44e22c2401cc62005dc1585172 to your computer and use it in GitHub Desktop.
Save Willy-JL/39ceae44e22c2401cc62005dc1585172 to your computer and use it in GitHub Desktop.
Colored console output with primer for windows' cmd
# Color escape code using rgb values (0-255)
def rgb(r, g, b):
return f'\x1b[38;2;{r};{g};{b}m'
# Primer for windows' cmd to enable color escape codes
import sys
if sys.platform == 'win32':
from ctypes import windll, c_int, byref, c_void_p
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
INVALID_HANDLE_VALUE = c_void_p(-1).value
STD_OUTPUT_HANDLE = c_int(-11)
hStdout = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
mode = c_int(0)
ok = windll.kernel32.GetConsoleMode(c_int(hStdout), byref(mode))
if ok:
mode = c_int(mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
ok = windll.kernel32.SetConsoleMode(c_int(hStdout), mode)
# Actually using it
from colorama import Fore
print(f'{rgb(0, 169, 255)}This is blue! {Fore.RESET}And this is back to white!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment