Claude Code for Enlighten: Terminal Progress Bars in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for Enlighten: Terminal Progress Bars in Python
AI

Claude Code for Enlighten: Terminal Progress Bars in Python

Published: March 23, 2028
Read time: 5 min read
By: Claude Skills 360

Enlighten renders multiple simultaneous terminal progress bars without garbling output. pip install enlighten. Basic: import enlighten; manager = enlighten.get_manager(); pbar = manager.counter(total=100, desc="Loading", unit="items"); pbar.update(); pbar.close(); manager.stop(). Format: bar_format="{desc}{desc_pad}{percentage:3.0f}%|{bar}| {count:{len_total}d}/{total} [{elapsed}<{eta}, {rate:.1f}{unit_pad}{unit}/s]". Color: color="green". Series: series=[" ","▏","▎","▍","▌","▋","▊","▉","█"]. Print: manager.print("log message") — prints above bars. pbar.print(msg). SubCounter: t1 = pbar.add_subcounter("green", all_fields=True); t2 = pbar.add_subcounter("red"); t1.update(); t2.update() — segmented bar. Nested: multiple manager.counter() calls stack bars vertically. StatusBar: manager.status_bar("Ready", static=True). Header: manager.counter(total=10, desc="Step 1") then second counter below. Stop: manager.stop() restores terminal. Thread-safe: manager handles concurrent .update() calls. Context: with enlighten.get_manager() as manager:. enabled=False for non-TTY. Rate: pbar.refresh() for forced redraw. Overhead: minimal; backed by a dedicated render thread. manager.counter(min_delta=0.1) — throttle refresh rate. Count: pbar.count. Elapsed: pbar.elapsed. ETa auto-computed. Claude Code generates Enlighten multi-bar progress UIs for batch jobs, pipelines, and concurrent downloaders.

CLAUDE.md for Enlighten

## Enlighten Stack
- Version: enlighten >= 1.12 | pip install enlighten
- Manager: manager = enlighten.get_manager() | with enlighten.get_manager() as manager:
- Counter: pbar = manager.counter(total=N, desc="...", unit="files", color="green")
- Update: pbar.update() | pbar.update(n) for batch | pbar.update(incr=5)
- Print: manager.print("log line") — displays above all bars without breaking them
- SubCounter: pbar.add_subcounter("green") / "red" / "yellow" for pass/fail/skip bars
- Cleanup: pbar.close() | manager.stop() — must call to restore terminal

Enlighten Multi-Bar Progress Pipeline

# app/progress.py — Enlighten multi-bar progress, sub-counters, and pipeline helpers
from __future__ import annotations

import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import contextmanager
from typing import Any, Callable, Iterable, Iterator, TypeVar

import enlighten

T = TypeVar("T")


# ─────────────────────────────────────────────────────────────────────────────
# 1. Manager helpers
# ─────────────────────────────────────────────────────────────────────────────

@contextmanager
def managed(enabled: bool | None = None) -> Iterator[enlighten.Manager]:
    """
    Context manager that creates and cleans up an Enlighten manager.
    enabled: None → auto, True/False → force.
    """
    import sys
    is_enabled = sys.stderr.isatty() if enabled is None else enabled
    manager = enlighten.get_manager(enabled=is_enabled)
    try:
        yield manager
    finally:
        manager.stop()


def make_counter(
    manager: enlighten.Manager,
    total: int,
    desc: str,
    unit: str = "items",
    color: str = "green",
    leave: bool = False,
    min_delta: float = 0.1,
) -> enlighten.Counter:
    """
    Create a standard progress counter.
    leave=True keeps the bar after completion.
    """
    return manager.counter(
        total=total,
        desc=desc,
        unit=unit,
        color=color,
        leave=leave,
        min_delta=min_delta,
    )


# ─────────────────────────────────────────────────────────────────────────────
# 2. Simple single-bar iteration
# ─────────────────────────────────────────────────────────────────────────────

def track(
    iterable: Iterable[T],
    desc: str = "Processing",
    unit: str = "it",
    color: str = "green",
    total: int | None = None,
) -> Iterator[T]:
    """
    Wrap an iterable with an Enlighten progress bar.

    Usage:
        for item in track(items, desc="Downloading", unit="files"):
            download(item)
    """
    items = list(iterable)
    n = total or len(items)
    with managed() as manager:
        pbar = make_counter(manager, total=n, desc=desc, unit=unit, color=color)
        for item in items:
            yield item
            pbar.update()
        pbar.close()


def process_items(
    items: list[T],
    fn: Callable[[T], Any],
    desc: str = "Processing",
    unit: str = "items",
    color: str = "green",
) -> list[Any]:
    """
    Apply fn to each item with a progress bar.
    Returns list of results.
    """
    with managed() as manager:
        pbar = make_counter(manager, total=len(items), desc=desc, unit=unit, color=color)
        results = []
        for item in items:
            results.append(fn(item))
            pbar.update()
        pbar.close()
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 3. Status bar + progress bar combo
# ─────────────────────────────────────────────────────────────────────────────

@contextmanager
def with_status(
    status_text: str,
    total: int,
    desc: str,
    unit: str = "items",
) -> Iterator[tuple[enlighten.Manager, enlighten.Counter]]:
    """
    Display a static status line above a progress bar.

    Usage:
        with with_status("🔄 Sync in progress", total=100, desc="Files") as (mgr, pbar):
            for f in files:
                process(f)
                pbar.update()
    """
    with managed() as manager:
        status = manager.status_bar(
            status_text,
            color="white_on_black",
            justify=enlighten.Justify.CENTER,
            static=True,
        )
        pbar = make_counter(manager, total=total, desc=desc, unit=unit)
        try:
            yield manager, pbar
        finally:
            pbar.close()
            status.close()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Sub-counter bars (pass / fail / skip)
# ─────────────────────────────────────────────────────────────────────────────

class TestResultBar:
    """
    Progress bar with green/red/yellow sub-counters for pass/fail/skip.

    Usage:
        with TestResultBar(total=len(tests)) as bar:
            for test in tests:
                result = run_test(test)
                bar.record(result)   # "pass" | "fail" | "skip"
        bar.summary()
    """

    def __init__(self, total: int, desc: str = "Tests"):
        self._total = total
        self._desc = desc
        self._manager: enlighten.Manager | None = None
        self._pbar = None
        self._pass_counter = None
        self._fail_counter = None
        self._skip_counter = None
        self._counts: dict[str, int] = {"pass": 0, "fail": 0, "skip": 0}

    def __enter__(self) -> "TestResultBar":
        self._manager = enlighten.get_manager()
        self._pbar = self._manager.counter(
            total=self._total,
            desc=self._desc,
            unit="tests",
            color="cyan",
            bar_format="{desc}{desc_pad}{percentage:3.0f}%|{bar}|"
                       " {count:{len_total}d}/{total} [{elapsed}<{eta}] "
                       "{pass_count}{fail_count}{skip_count} ⊘",
        )
        self._pass_counter = self._pbar.add_subcounter("green")
        self._fail_counter = self._pbar.add_subcounter("red")
        self._skip_counter = self._pbar.add_subcounter("yellow")
        return self

    def record(self, result: str) -> None:
        """result: 'pass', 'fail', or 'skip'."""
        self._counts[result] = self._counts.get(result, 0) + 1
        if result == "pass":
            self._pass_counter.update()
        elif result == "fail":
            self._fail_counter.update()
        else:
            self._skip_counter.update()

    def summary(self) -> dict[str, int]:
        return dict(self._counts)

    def __exit__(self, *_):
        if self._pbar:
            self._pbar.close()
        if self._manager:
            self._manager.stop()


# ─────────────────────────────────────────────────────────────────────────────
# 5. Multi-stage pipeline
# ─────────────────────────────────────────────────────────────────────────────

def run_pipeline(
    stages: list[tuple[str, Callable[[Any], Any], Any]],
    unit: str = "items",
) -> list[Any]:
    """
    Run a sequence of (label, fn, items) stages with stacked progress bars.

    Each stage's bar appears below the previous, all visible simultaneously.
    """
    with managed() as manager:
        counters = []
        for label, fn, items in stages:
            pbar = make_counter(
                manager,
                total=len(items),
                desc=label,
                unit=unit,
                leave=True,
            )
            counters.append((pbar, fn, items))

        all_results = []
        for pbar, fn, items in counters:
            stage_results = []
            for item in items:
                stage_results.append(fn(item))
                pbar.update()
            pbar.close()
            all_results.append(stage_results)

        return all_results


# ─────────────────────────────────────────────────────────────────────────────
# 6. Concurrent progress (ThreadPoolExecutor)
# ─────────────────────────────────────────────────────────────────────────────

def parallel_process(
    items: list[T],
    fn: Callable[[T], Any],
    desc: str = "Processing",
    unit: str = "items",
    max_workers: int = 4,
    color: str = "blue",
) -> list[Any]:
    """
    Process items concurrently with a thread pool, showing live progress.
    Thread-safe: Enlighten handles concurrent .update() calls.
    """
    with managed() as manager:
        pbar = make_counter(
            manager, total=len(items), desc=desc, unit=unit, color=color
        )
        results = [None] * len(items)
        indexed = list(enumerate(items))

        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            futures = {executor.submit(fn, item): idx for idx, item in indexed}
            for future in as_completed(futures):
                idx = futures[future]
                try:
                    results[idx] = future.result()
                except Exception as exc:
                    manager.print(f"  Error on item {idx}: {exc}")
                    results[idx] = None
                pbar.update()

        pbar.close()
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 7. Logging integration
# ─────────────────────────────────────────────────────────────────────────────

class ProgressLogger:
    """
    Combines Enlighten progress with manager.print() for clean log messages
    that appear above the progress bar without breaking animation.

    Usage:
        with ProgressLogger(total=100, desc="Importing") as pl:
            for row in rows:
                process(row)
                pl.progress()
                if row.warning:
                    pl.warn(f"  Skipped: {row.id}")
    """

    def __init__(self, total: int, desc: str = "Processing", unit: str = "items"):
        self._total = total
        self._desc = desc
        self._unit = unit
        self._manager: enlighten.Manager | None = None
        self._pbar = None

    def __enter__(self) -> "ProgressLogger":
        self._manager = enlighten.get_manager()
        self._pbar = make_counter(
            self._manager, self._total, self._desc, self._unit
        )
        return self

    def progress(self, n: int = 1) -> None:
        self._pbar.update(n)

    def log(self, msg: str) -> None:
        self._manager.print(msg)

    def warn(self, msg: str) -> None:
        self._manager.print(f"⚠  {msg}")

    def error(self, msg: str) -> None:
        self._manager.print(f"✗  {msg}")

    def __exit__(self, *_):
        if self._pbar:
            self._pbar.close()
        if self._manager:
            self._manager.stop()


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    DELAY = 0.02

    print("=== Single progress bar ===")
    with managed() as manager:
        pbar = make_counter(manager, total=30, desc="Downloading", unit="files", color="green")
        for _ in range(30):
            time.sleep(DELAY)
            pbar.update()
        pbar.close()

    print("\n=== Status bar + progress ===")
    with with_status("🔄 Sync job running", total=20, desc="Records", unit="rows") as (mgr, pbar):
        for i in range(20):
            time.sleep(DELAY)
            if i % 5 == 0:
                mgr.print(f"  Checkpoint at row {i}")
            pbar.update()

    print("\n=== Sub-counters (pass/fail/skip) ===")
    import random
    with TestResultBar(total=30, desc="Test Suite") as bar:
        for _ in range(30):
            time.sleep(DELAY)
            bar.record(random.choice(["pass", "pass", "pass", "fail", "skip"]))
    counts = bar.summary()
    print(f"  Results: {counts}")

    print("\n=== Multi-stage pipeline ===")
    stage_data = list(range(15))
    run_pipeline([
        ("Stage 1: Extract", lambda x: x * 2,              stage_data),
        ("Stage 2: Transform", lambda x: x + 1,            stage_data),
        ("Stage 3: Load",    lambda x: time.sleep(DELAY),  stage_data),
    ])

    print("\n=== Concurrent processing ===")
    items = list(range(20))
    results = parallel_process(
        items,
        fn=lambda x: (time.sleep(DELAY), x ** 2)[1],
        desc="Parallel compute",
        unit="tasks",
        max_workers=4,
    )
    print(f"  Sample results: {results[:5]}")

    print("\n=== ProgressLogger ===")
    with ProgressLogger(total=20, desc="Importing rows") as pl:
        for i in range(20):
            time.sleep(DELAY)
            pl.progress()
            if i % 7 == 0:
                pl.warn(f"Null value in row {i}")
    print("  Done")

For the tqdm alternative — tqdm is the most widely used Python progress bar and has the richest ecosystem (pandas integration, Jupyter notebook display, auto-detection for scripts vs notebooks), but multiple simultaneous tqdm bars can interfere with each other in some terminals; Enlighten is specifically designed for multi-bar scenarios with a dedicated render thread that keeps bars from overwriting each other, making it better for pipeline stages and test runners where you want several bars visible at once. For the rich.progress alternative — rich.Progress supports color, columns, spinners within bars, and integrates with rich’s Live layout, making it the best choice when your CLI already uses rich for other output; Enlighten exists as a standalone library with zero rich dependency, thinner footprint, and manager.print() that reliably interleaves log messages with live bars — use Enlighten when you need robust multi-bar output without pulling in the entire rich ecosystem. The Claude Skills 360 bundle includes Enlighten skill sets covering enlighten.get_manager(), Counter with total/desc/unit/color, managed() context manager, make_counter() factory, track() iterable wrapper, process_items() with fn, with_status() status bar combo, TestResultBar pass/fail/skip sub-counters, run_pipeline() stacked multi-stage bars, parallel_process() thread pool with progress, ProgressLogger for manager.print() log messages, and min_delta throttling. Start with the free tier to try multi-bar terminal progress 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