colorama adds cross-platform ANSI color codes to Python terminal output. pip install colorama. Init: from colorama import init, Fore, Back, Style; init(). On Windows, init() patches stdout/stderr to translate ANSI codes. init(autoreset=True) — automatically resets color after each print. Colors: print(Fore.RED + "error"). print(Fore.GREEN + "ok"). print(Fore.BLUE + "info"). print(Fore.YELLOW + "warning"). Background: print(Back.RED + "highlight"). Style: print(Style.BRIGHT + "bold"). print(Style.DIM + "muted"). print(Style.RESET_ALL) — clear all. Extended: Fore.LIGHTRED_EX, Fore.LIGHTGREEN_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTMAGENTA_EX. F-string: print(f"{Fore.GREEN}OK{Style.RESET_ALL}: {msg}"). Reset inline: f"{Fore.RED}error{Style.RESET_ALL}". CI/strip: init(strip=True) — strips all ANSI codes, plain text output. init(strip=not sys.stdout.isatty()) — auto-detect TTY. deinit() — restore original stdout. Logging: subclass Formatter, override format, prepend Fore.COLOR based on record.levelno. colorize(text) helper. All foreground: BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE + LIGHTX_EX variants. Reset between calls: print(Fore.RED + "text" + Style.RESET_ALL) or use autoreset=True. Claude Code generates colorama initializers, colored formatters, and styled CLI output functions.
CLAUDE.md for colorama
## colorama Stack
- Version: colorama >= 0.4.6 | pip install colorama
- Init: colorama.init(autoreset=True) — call once at startup; autoreset avoids manual RESET_ALL
- Colors: Fore.RED / Fore.GREEN / Fore.YELLOW / Fore.BLUE / Fore.CYAN / Fore.MAGENTA
- Bright: Style.BRIGHT + Fore.X for bold color | Style.DIM for muted
- Reset: Style.RESET_ALL — explicit reset when autoreset=False
- CI: init(strip=not sys.stdout.isatty()) — strip codes when not interactive
- Logging: subclass logging.Formatter, prepend Fore.COLOR based on record.levelno
colorama Colored Output Pipeline
# app/colors.py — colorama colored terminal output, logging formatter, and CLI helpers
from __future__ import annotations
import logging
import sys
from typing import Any
import colorama
from colorama import Back, Fore, Style, init
# ─────────────────────────────────────────────────────────────────────────────
# 1. Initialization
# ─────────────────────────────────────────────────────────────────────────────
def setup(autoreset: bool = True, strip: bool | None = None) -> None:
"""
Call once at application startup.
autoreset=True resets color after every print — avoids leaking colors.
strip=None → auto-detect: strip codes when not writing to a TTY
(redirected output, CI logs) so they don't appear as garbled escape sequences.
"""
if strip is None:
strip = not sys.stdout.isatty()
init(autoreset=autoreset, strip=strip)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Color constants / palette
# ─────────────────────────────────────────────────────────────────────────────
# Standard 8 foreground colors
RED = Fore.RED
GREEN = Fore.GREEN
YELLOW = Fore.YELLOW
BLUE = Fore.BLUE
MAGENTA = Fore.MAGENTA
CYAN = Fore.CYAN
WHITE = Fore.WHITE
BLACK = Fore.BLACK
# Bright ("light") variants — more vivid on most terminals
LRED = Fore.LIGHTRED_EX
LGREEN = Fore.LIGHTGREEN_EX
LYELLOW = Fore.LIGHTYELLOW_EX
LBLUE = Fore.LIGHTBLUE_EX
LMAGENTA = Fore.LIGHTMAGENTA_EX
LCYAN = Fore.LIGHTCYAN_EX
LWHITE = Fore.LIGHTWHITE_EX
RESET = Style.RESET_ALL
BRIGHT = Style.BRIGHT
DIM = Style.DIM
# ─────────────────────────────────────────────────────────────────────────────
# 3. Colorize helper
# ─────────────────────────────────────────────────────────────────────────────
def colorize(text: str, color: str, bright: bool = False) -> str:
"""
Wrap text with a color code and RESET_ALL at the end.
bright=True prepends Style.BRIGHT for a bolder variant.
"""
prefix = (Style.BRIGHT if bright else "") + color
return f"{prefix}{text}{Style.RESET_ALL}"
def colored(text: str, fg: str = "", bg: str = "", bold: bool = False) -> str:
"""Compose foreground + background + bold into a single styled string."""
parts = []
if bold:
parts.append(Style.BRIGHT)
if fg:
parts.append(fg)
if bg:
parts.append(bg)
return "".join(parts) + text + Style.RESET_ALL
# ─────────────────────────────────────────────────────────────────────────────
# 4. Semantic print helpers
# ─────────────────────────────────────────────────────────────────────────────
def print_success(msg: str, prefix: str = "✓") -> None:
print(colorize(f"{prefix} {msg}", Fore.GREEN, bright=True))
def print_error(msg: str, prefix: str = "✗") -> None:
print(colorize(f"{prefix} {msg}", Fore.RED, bright=True), file=sys.stderr)
def print_warning(msg: str, prefix: str = "⚠") -> None:
print(colorize(f"{prefix} {msg}", Fore.YELLOW))
def print_info(msg: str, prefix: str = "→") -> None:
print(colorize(f"{prefix} {msg}", Fore.CYAN))
def print_header(title: str, width: int = 60) -> None:
bar = "─" * width
print(colored(bar, fg=Fore.BLUE, bold=True))
print(colored(f" {title}", fg=Fore.BLUE, bold=True))
print(colored(bar, fg=Fore.BLUE, bold=True))
def print_kv(key: str, value: Any, key_width: int = 20) -> None:
"""Print a key/value pair with distinct colors."""
k = colorize(f"{key:<{key_width}}", Fore.CYAN)
v = colorize(str(value), Fore.WHITE)
print(f"{k}: {v}")
# ─────────────────────────────────────────────────────────────────────────────
# 5. Status table
# ─────────────────────────────────────────────────────────────────────────────
def print_status_table(rows: list[dict], columns: list[str] | None = None) -> None:
"""
Print a colored table where rows with status="error" are red,
status="ok"/"success" are green, and status="warn" are yellow.
"""
if not rows:
return
columns = columns or list(rows[0].keys())
# Header
header = " ".join(colorize(f"{col:15}", Fore.CYAN, bright=True) for col in columns)
print(header)
print(colorize("─" * (17 * len(columns)), Fore.BLUE))
# Rows
STATUS_COLORS = {
"ok": Fore.GREEN,
"success": Fore.GREEN,
"error": Fore.RED,
"fail": Fore.RED,
"warn": Fore.YELLOW,
"warning": Fore.YELLOW,
"skip": Fore.MAGENTA,
}
for row in rows:
status = str(row.get("status", "")).lower()
row_color = STATUS_COLORS.get(status, Fore.WHITE)
cells = " ".join(colorize(f"{str(row.get(col, '')):15}", row_color) for col in columns)
print(cells)
# ─────────────────────────────────────────────────────────────────────────────
# 6. Colored logging formatter
# ─────────────────────────────────────────────────────────────────────────────
class ColoredFormatter(logging.Formatter):
"""
logging.Formatter subclass that prepends a color code based on log level.
Install with:
handler = logging.StreamHandler()
handler.setFormatter(ColoredFormatter("%(levelname)s: %(message)s"))
logging.getLogger().addHandler(handler)
"""
LEVEL_COLORS = {
logging.DEBUG: Fore.BLUE,
logging.INFO: Fore.GREEN,
logging.WARNING: Fore.YELLOW,
logging.ERROR: Fore.RED,
logging.CRITICAL: Fore.RED + Style.BRIGHT,
}
def format(self, record: logging.LogRecord) -> str:
color = self.LEVEL_COLORS.get(record.levelno, "")
message = super().format(record)
return f"{color}{message}{Style.RESET_ALL}"
def make_colored_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
"""Create a logger that outputs colored messages to stderr."""
logger = logging.getLogger(name)
logger.setLevel(level)
if not logger.handlers:
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(
ColoredFormatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")
)
logger.addHandler(handler)
return logger
# ─────────────────────────────────────────────────────────────────────────────
# 7. Progress indicator (simple, no dependencies)
# ─────────────────────────────────────────────────────────────────────────────
def print_step(step: int, total: int, label: str, ok: bool = True) -> None:
"""Print a numbered step with pass/fail coloring."""
status = colorize("PASS", Fore.GREEN, bright=True) if ok else colorize("FAIL", Fore.RED, bright=True)
num = colorize(f"[{step}/{total}]", Fore.CYAN)
print(f"{num} {label:40} {status}")
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
setup(autoreset=True, strip=False)
print_header("colorama Demo")
print("\n=== Semantic helpers ===")
print_success("All tests passed")
print_error("Connection refused")
print_warning("Disk usage above 80%")
print_info("Starting server on port 8000")
print("\n=== Key/Value display ===")
print_kv("database", "postgresql://localhost/mydb")
print_kv("workers", 4)
print_kv("debug", False)
print("\n=== Status table ===")
checks = [
{"service": "database", "status": "ok", "latency": "3 ms"},
{"service": "redis", "status": "ok", "latency": "1 ms"},
{"service": "email", "status": "warn", "latency": "250 ms"},
{"service": "payment", "status": "error", "latency": "timeout"},
{"service": "storage", "status": "skip", "latency": "—"},
]
print_status_table(checks)
print("\n=== Steps ===")
steps = [("Lint", True), ("Type check", True), ("Tests", True), ("Build", False)]
for i, (label, ok) in enumerate(steps, 1):
print_step(i, len(steps), label, ok=ok)
print("\n=== Colored logging ===")
log = make_colored_logger("demo")
log.debug("Debug message")
log.info("Server started")
log.warning("Memory high")
log.error("Request failed")
print("\n=== All foreground colors ===")
colors = [
(Fore.BLACK, "BLACK"), (Fore.RED, "RED"),
(Fore.GREEN, "GREEN"), (Fore.YELLOW, "YELLOW"),
(Fore.BLUE, "BLUE"), (Fore.MAGENTA, "MAGENTA"),
(Fore.CYAN, "CYAN"), (Fore.WHITE, "WHITE"),
(Fore.LIGHTRED_EX, "LRED"), (Fore.LIGHTGREEN_EX, "LGREEN"),
(Fore.LIGHTYELLOW_EX, "LYELLOW"),(Fore.LIGHTBLUE_EX, "LBLUE"),
(Fore.LIGHTMAGENTA_EX, "LMAGENTA"),(Fore.LIGHTCYAN_EX, "LCYAN"),
]
for fg, name in colors:
print(f" {fg}{name}{Style.RESET_ALL}", end=" ")
print()
For the rich alternative — Rich provides a much richer terminal rendering system with markup ([bold red]text[/]), tables, spinners, progress bars, syntax highlighting, and panels, while colorama is the right choice when you need lightweight, no-dependency color injection into existing print() calls — colorama.init() + Fore.GREEN + text + Style.RESET_ALL is 2 lines, works cross-platform (including Windows cmd.exe), and doesn’t require learning a new markup language or restructuring output code. For the termcolor alternative — termcolor exposes a colored(text, color, on_color, attrs) function that wraps text with ANSI codes but does not handle Windows ANSI translation, making it Unix-only without a compatibility layer; colorama’s init() patches sys.stdout on Windows so the same Fore.RED + text pattern works identically across platforms — the key value of colorama is cross-platform compatibility, not a richer API. The Claude Skills 360 bundle includes colorama skill sets covering init() with autoreset and strip params, Fore/Back/Style constants for all 16 colors, colorize() helper with RESET_ALL, semantic print_success/error/warning/info helpers, colored() for multi-attribute composition, print_status_table with status-based row coloring, ColoredFormatter for logging.Formatter subclass, make_colored_logger setup, CI-aware strip=not isatty() initialization, and print_step numbered progress display. Start with the free tier to try cross-platform terminal color code generation.