Claude Code for colorama: Cross-Platform Terminal Colors — Claude Skills 360 Blog
Blog / AI / Claude Code for colorama: Cross-Platform Terminal Colors
AI

Claude Code for colorama: Cross-Platform Terminal Colors

Published: February 14, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free