Claude Code for alive-progress: Animated Python Progress Bars — Claude Skills 360 Blog
Blog / AI / Claude Code for alive-progress: Animated Python Progress Bars
AI

Claude Code for alive-progress: Animated Python Progress Bars

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

alive-progress renders animated terminal progress bars. pip install alive-progress. Basic: from alive_progress import alive_bar. with alive_bar(total) as bar: for item in items: process(item); bar(). Manual: with alive_bar(100) as bar: bar(10) — advance by 10. Unknown total: with alive_bar() as bar: bar(). Title: with alive_bar(total, title="Processing") as bar:. Bar style: with alive_bar(total, bar="smooth") as bar:. bar="classic", "blocks", "bubbles", "filling", "notes", "ruler". Spinner: spinner="classic", "dots", "waves", "stars", "triangles", "wait". Stats: with alive_bar(total, stats=True) as bar: — shows rate and ETA. stats="(eta:{eta} rate:{rate})". Elapsed: elapsed=True. Text: bar.text("Processing {item}") or bar.text = f"item {i}". Receipt: with alive_bar(total, receipt=True) as bar: — final summary line. Force CI: with alive_bar(total, force_tty=True) as bar: — output even when not TTY. Disable: with alive_bar(total, disable=not sys.stdout.isatty()) as bar:. Dual line: with alive_bar(total, dual_line=True) as bar: bar.text = "detail". Theme: with alive_bar(total, theme="smooth") as bar:. theme="classic", "musical". Monitor: with alive_bar(total, monitor=True) as bar: — shows count. monitor="{count} / {total} [{percent:.0f}%]". Config: from alive_progress import config_handler; config_handler.set_global(spinner="dots", bar="smooth"). Claude Code generates alive_bar wrappers, dual-line status displays, and batch processing pipelines.

CLAUDE.md for alive-progress

## alive-progress Stack
- Version: alive-progress >= 3.1 | pip install alive-progress
- Basic: with alive_bar(len(items), title="Label") as bar: ... bar()
- Manual: bar(n) to advance by n steps; bar(0) to pulse without advancing
- Unknown: with alive_bar() as bar: bar() — spinner only, no ETA
- Text: bar.text = f"current: {item}" — live status below the bar
- Style: bar="smooth" | spinner="dots" | theme="smooth"
- CI: force_tty=True | disable=not sys.stdout.isatty()

alive-progress Animation Pipeline

# app/progress_alive.py — alive-progress bar patterns
from __future__ import annotations

import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Callable, Iterable, Iterator

from alive_progress import alive_bar, config_handler


# ─────────────────────────────────────────────────────────────────────────────
# Global config (optional — set project-wide defaults)
# ─────────────────────────────────────────────────────────────────────────────

config_handler.set_global(
    spinner="dots",
    bar="smooth",
    elapsed=True,
    stats=True,
    receipt=True,
    force_tty=False,   # set True in CI if you want progress in logs
)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic iteration — wrapping a loop
# ─────────────────────────────────────────────────────────────────────────────

def process_items(items: list[Any]) -> list[Any]:
    """
    alive_bar wraps a total count. Call bar() once per completed item.
    Shows animated spinner, filled bar, items/sec rate, and ETA.
    """
    results = []
    with alive_bar(len(items), title="Processing", bar="smooth") as bar:
        for item in items:
            time.sleep(0.02)   # simulate work
            results.append({"item": item, "done": True})
            bar()
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 2. Manual advance — progress += N per step
# ─────────────────────────────────────────────────────────────────────────────

def process_batches(records: list[dict], batch_size: int = 50) -> list[dict]:
    """
    bar(n) advances the bar by n units — useful when each iteration
    processes a variable number of records.
    """
    results: list[dict] = []
    batches = [records[i:i + batch_size] for i in range(0, len(records), batch_size)]

    with alive_bar(len(records), title="Batch processing", bar="blocks") as bar:
        for batch in batches:
            time.sleep(0.01 * len(batch))
            results.extend({"processed": True, **r} for r in batch)
            bar(len(batch))    # advance by actual batch size
            bar.text = f"batch size={len(batch)}"

    return results


# ─────────────────────────────────────────────────────────────────────────────
# 3. Unknown total — spinner only
# ─────────────────────────────────────────────────────────────────────────────

def stream_events(event_count: int = 20) -> list[dict]:
    """
    When total is unknown, omit the total argument.
    alive_bar shows an animated spinner and elapsed time, no ETA.
    """
    events: list[dict] = []
    with alive_bar(title="Streaming events", spinner="waves") as bar:
        for i in range(event_count):
            time.sleep(0.05)
            events.append({"id": i, "type": "user.action"})
            bar()
            bar.text = f"event #{i}"
    return events


# ─────────────────────────────────────────────────────────────────────────────
# 4. Dual-line display — bar + status line
# ─────────────────────────────────────────────────────────────────────────────

def train_epochs(
    epochs: int = 5,
    steps_per_epoch: int = 20,
) -> list[dict]:
    """
    dual_line=True shows a second line below the bar for detailed status.
    Use bar.text for the status line — it updates live without clearing.
    """
    history: list[dict] = []
    with alive_bar(
        epochs * steps_per_epoch,
        title="Training",
        dual_line=True,
        bar="filling",
        spinner="stars",
    ) as bar:
        for epoch in range(epochs):
            epoch_loss = 0.0
            for step in range(steps_per_epoch):
                time.sleep(0.005)
                loss = 1.0 / (epoch * steps_per_epoch + step + 1) + 0.01
                epoch_loss += loss
                bar()
                bar.text = f"epoch={epoch+1} step={step+1} loss={loss:.4f}"
            avg_loss = epoch_loss / steps_per_epoch
            history.append({"epoch": epoch + 1, "loss": round(avg_loss, 4)})

    return history


# ─────────────────────────────────────────────────────────────────────────────
# 5. Byte download simulation
# ─────────────────────────────────────────────────────────────────────────────

def simulate_download(total_bytes: int = 1_048_576) -> None:
    """
    Combine bar(chunk) with bar.text showing transfer speed for file downloads.
    """
    chunk_size = 65_536   # 64 KB chunks
    received   = 0

    with alive_bar(
        total_bytes,
        title="Downloading",
        bar="bubbles",
        stats="({rate}/s)",
        monitor="{count}/{total} bytes",
    ) as bar:
        while received < total_bytes:
            chunk = min(chunk_size, total_bytes - received)
            time.sleep(0.02)
            received += chunk
            bar(chunk)
            bar.text = f"{received // 1024} KB / {total_bytes // 1024} KB"


# ─────────────────────────────────────────────────────────────────────────────
# 6. concurrent.futures — progress on parallel tasks
# ─────────────────────────────────────────────────────────────────────────────

def _fetch(url: str) -> dict:
    time.sleep(0.05)
    return {"url": url, "status": 200}


def parallel_fetch(urls: list[str], max_workers: int = 8) -> list[dict]:
    """
    Wrap as_completed with alive_bar — bar advances each time a future resolves.
    """
    results: list[dict] = []
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(_fetch, url): url for url in urls}
        with alive_bar(len(futures), title="Fetching", bar="notes") as bar:
            for future in as_completed(futures):
                try:
                    results.append(future.result())
                except Exception as exc:
                    bar.text = f"ERROR: {exc}"
                finally:
                    bar()
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 7. CI-safe wrapper — disable when not interactive
# ─────────────────────────────────────────────────────────────────────────────

def progress_iter(
    items: Iterable[Any],
    total: int | None = None,
    title: str = "Working",
    force_tty: bool = False,
) -> Iterator[Any]:
    """
    Yields items from an iterable, showing progress.
    In CI (non-TTY), force_tty=False suppresses animation — no garbled output.
    Pass force_tty=True to keep progress in CI logs.
    """
    is_tty = sys.stdout.isatty() or force_tty
    items_list = list(items)
    actual_total = total or len(items_list)

    with alive_bar(
        actual_total,
        title=title,
        disable=not is_tty,
        force_tty=force_tty,
    ) as bar:
        for item in items_list:
            yield item
            bar()


# ─────────────────────────────────────────────────────────────────────────────
# 8. File processing pipeline
# ─────────────────────────────────────────────────────────────────────────────

def process_directory(
    directory: Path,
    pattern: str = "*.txt",
    processor: Callable[[Path], Any] | None = None,
) -> list[dict]:
    """Process all matching files with a progress bar showing file names."""
    if processor is None:
        processor = lambda p: {"path": str(p), "size": p.stat().st_size}

    files  = list(directory.glob(pattern))
    results: list[dict] = []

    with alive_bar(len(files), title=f"Processing {pattern}", dual_line=True) as bar:
        for f in files:
            bar.text = f.name
            try:
                results.append(processor(f))
            except Exception as exc:
                bar.text = f"ERROR {f.name}: {exc}"
            finally:
                bar()

    return results


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

if __name__ == "__main__":
    print("=== Basic iteration ===")
    results = process_items(list(range(15)))
    print(f"  Processed {len(results)} items")

    print("\n=== Dual-line training ===")
    history = train_epochs(epochs=3, steps_per_epoch=10)
    for h in history:
        print(f"  epoch={h['epoch']} loss={h['loss']}")

    print("\n=== Parallel fetch ===")
    urls = [f"https://api.example.com/{i}" for i in range(12)]
    fetched = parallel_fetch(urls, max_workers=4)
    print(f"  Fetched {len(fetched)} URLs")

    print("\n=== Download ===")
    simulate_download(total_bytes=262_144)

    print("\n=== CI-safe iterator ===")
    for item in progress_iter(range(8), title="CI test", force_tty=True):
        time.sleep(0.02)
    print("  Done")

For the tqdm alternative — tqdm is the most widely-used Python progress library with native pandas.progress_apply, asyncio, and concurrent.futures integrations, while alive-progress renders smoother animated spinners using ANSI escape sequences, provides dual_line=True for a two-line display (bar + live status text), and shows a clean formatted receipt summary at completion — the visual difference is most apparent in terminal emulators with full ANSI support where alive-progress animations are noticeably smoother. For the print(f"{i}/{total}") alternative — manual print-based progress clutters stdout with one line per item, cannot show ETA or throughput, and cannot be easily suppressed in CI, while with alive_bar(total, disable=not sys.stdout.isatty()) as bar: outputs a single updating line in interactive mode and nothing at all in CI piped environments. The Claude Skills 360 bundle includes alive-progress skill sets covering alive_bar with total count, manual bar(n) advancement by variable step sizes, unknown total spinner mode, dual_line with bar.text status, bar/spinner/theme style selection, receipt completion summary, force_tty and disable for CI output control, concurrent.futures as_completed wrapping, byte-level download progress with monitor format, progress_iter generator wrapper, and config_handler.set_global for project-wide defaults. Start with the free tier to try animated progress bar 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