ANSI escape codes in Python
Python's stdlib has no built-in colour helper, but every byte you would write by hand is fine — strings can carry \x1b escapes directly. For cross-platform support (Windows cmd.exe before 1909 didn't parse ANSI by default), reach for colorama. For richer TUIs, rich and prompt_toolkit build on the same byte forms documented here.
Recommended libraries
- colorama
Cross-platform ANSI shim: on Windows it translates escapes into Win32 console API calls; elsewhere it's a no-op.
init()once at module load. - rich
High-level console toolkit (colour, tables, progress bars, markdown). Emits standard ANSI under the hood; auto-detects terminal capability.
- termcolor
Tiny single-purpose helper:
colored('text', 'red', attrs=['bold']). No state, no init, ~150 lines of code. - prompt_toolkit
Full-screen TUI framework — REPLs (ipython, pgcli), editors, dialogs. Handles input parsing including bracketed paste and mouse.
Idiomatic patterns
print('\x1b[1;31merror:\x1b[0m permission denied')from colorama import init, Fore, Style
init() # no-op on POSIX, enables ANSI on legacy Windows
print(f'{Style.BRIGHT}{Fore.RED}error:{Style.RESET_ALL} permission denied')import sys, time
for i in range(101):
# \r returns to col 1, \x1b[K erases to end of line
sys.stdout.write(f'\r\x1b[K{i}%')
sys.stdout.flush()
time.sleep(0.02)
print()import os, sys
USE_COLOR = sys.stdout.isatty() and 'NO_COLOR' not in os.environ
def style(text: str, sgr: str) -> str:
return f'\x1b[{sgr}m{text}\x1b[0m' if USE_COLOR else text
print(style('OK', '32'))