Spinner¶
An indeterminate progress spinner for blocking work whose duration is unknown: a subprocess, a network call, a long query. Where click.progressbar needs a known length or an iterable to advance through, Spinner simply signals that something is happening.
It animates on a background thread, so the calling thread stays free to block on the work itself:
from time import sleep
from click_extra import Spinner
with Spinner("Brewing tea"):
sleep(5)
The spinner draws to stderr and is a no-op whenever that stream is not a terminal (a pipe, a file, a CI log), so redirected output and machine-readable formats stay clean. Reassign its label while it runs to reflect the current step, and set a delay so it only appears once an operation is genuinely slow.
Use as a decorator¶
A Spinner doubles as a decorator, with or without parentheses. @Spinner wraps a function directly; @Spinner("…") configures the spinner first. Either way the function spins for the duration of every call and returns its result untouched.
@Spinner # Bare form: a default spinner.
def roast(batch):
sleep(5)
return batch
@Spinner("Roasting coffee", timer=True) # Configured form.
def roast_slowly(batch):
sleep(5)
return batch
The one instance is shared across calls, which is right for sequential use; give concurrent callers their own spinner.
Spin direction¶
Pass reverse=True to rotate the other way. It works with the default frames or any custom sequence:
with Spinner("Chilling lemonade", reverse=True):
sleep(5)
A clock is the clearest thing to run backwards, since a reader already knows which way its hands are supposed to go:
This is why the catalog carries no timeTravel. cli-spinners ships one, because its renderers only play frames forwards and a backwards clock has to be a second preset to exist at all. Here it is SPINNERS["clock"] with reverse=True, and a duplicate entry would only be a second name for the same animation.
The animation source is just a sequence of strings. click_extra.spinner ships the default Braille SPINNER_FRAMES and a plain ASCII_SPINNER_FRAMES for terminals without Unicode glyphs; pass your own to frames for anything else.
Picturing a spinner¶
frame_lines() hands back one turn of the animation held still, one line per frame. The glyph, the label, the style and the timer land where the running spinner puts them, reverse included, so the picture cannot drift from what the terminal shows. No thread starts and no terminal is needed:
from click_extra import SPINNERS, Spinner, Style
spinner = Spinner("Brewing tea", spinner=SPINNERS["moon"], style=Style(fg="green"))
lines = spinner.frame_lines()
Colors are applied by default, whatever stream the spinner itself would have drawn on: a picture carries its own answer to whether ANSI survives. Pass color=False for the bare text. These lines are what an animated capture stacks into an SVG.
A documentation page asks for that picture with :screenshot-animate:, naming the spinner to draw. The option takes the frames and the interval straight off it, so the image below is built from the same object the paragraph above describes:
Because the frames come from a declared spinner rather than from a timed recording, the same expression composes the same lines on every build. The committed asset keeps the same bytes, and the working tree stays clean: its @generated stamp names no release, so a new Click Extra version does not rewrite it.
Spinner catalog¶
SPINNERS is a catalog of around 90 ready-made animations, each a SpinnerPreset bundling the frames and the interval they were tuned for. They are ported from cli-spinners, the de-facto reference collection. Pick one with spinner=:
from click_extra import Spinner, SPINNERS
with Spinner("Brewing tea", spinner=SPINNERS["moon"]):
sleep(5)
The preset sets both the frames and the interval; an explicit frames= or interval= still overrides it. Because the spinner redraws the whole line instead of backspacing, the multi-character animations (bouncing-bar, pong, shark, …) render correctly here, unlike in the upstream renderers that had to drop them.
Full inventory¶
Every style is browsable from the CLI. On an interactive terminal click-extra spinner animates a live tour of the selection (--all for the whole catalog, --random N for a sample, or --select name1,name2 for specific ones); --table prints the reference table below instead of animating. The Frames column previews each animation, and the Tour column is the dwell time the live tour spends on each: three full cycles, clamped to two-to-three seconds:
$ click-extra --color spinner --all --table
╭───────────────────────┬──────────────────────────────────────────────────────────────────┬──────────┬───────╮
│ Name │ Frames │ Interval │ Tour │
├───────────────────────┼──────────────────────────────────────────────────────────────────┼──────────┼───────┤
│ dots │ ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏ │ 0.08s │ 2.4s │
│ dots2 │ ⣾ ⣽ ⣻ ⢿ ⡿ ⣟ ⣯ ⣷ │ 0.08s │ 2.0s │
│ dots3 │ ⠋ ⠙ ⠚ ⠞ ⠖ ⠦ ⠴ ⠲ ⠳ ⠓ │ 0.08s │ 2.4s │
│ dots4 │ ⠄ ⠆ ⠇ ⠋ ⠙ ⠸ ⠰ ⠠ ⠰ ⠸ ⠙ ⠋ ⠇ ⠆ │ 0.08s │ 3.0s │
│ dots5 │ ⠋ ⠙ ⠚ ⠒ ⠂ ⠂ ⠒ ⠲ ⠴ ⠦ ⠖ ⠒ ⠐ ⠐ ⠒ ⠓ ⠋ │ 0.08s │ 3.0s │
│ dots6 │ ⠁ ⠉ ⠙ ⠚ ⠒ ⠂ ⠂ ⠒ ⠲ ⠴ ⠤ ⠄ ⠄ ⠤ ⠴ ⠲ ⠒ ⠂ ⠂ ⠒ ⠚ ⠙ ⠉ ⠁ │ 0.08s │ 3.0s │
│ dots7 │ ⠈ ⠉ ⠋ ⠓ ⠒ ⠐ ⠐ ⠒ ⠖ ⠦ ⠤ ⠠ ⠠ ⠤ ⠦ ⠖ ⠒ ⠐ ⠐ ⠒ ⠓ ⠋ ⠉ ⠈ │ 0.08s │ 3.0s │
│ dots8 │ ⠁ ⠁ ⠉ ⠙ ⠚ ⠒ ⠂ ⠂ ⠒ ⠲ ⠴ ⠤ ⠄ ⠄ ⠤ ⠠ ⠠ ⠤ ⠦ ⠖ ⠒ ⠐ ⠐ ⠒ ⠓ ⠋ ⠉ ⠈ … (+1) │ 0.08s │ 3.0s │
│ dots9 │ ⢹ ⢺ ⢼ ⣸ ⣇ ⡧ ⡗ ⡏ │ 0.08s │ 2.0s │
│ dots10 │ ⢄ ⢂ ⢁ ⡁ ⡈ ⡐ ⡠ │ 0.08s │ 2.0s │
│ dots11 │ ⠁ ⠂ ⠄ ⡀ ⢀ ⠠ ⠐ ⠈ │ 0.1s │ 2.4s │
│ dots12 │ ⢀⠀ ⡀⠀ ⠄⠀ ⢂⠀ ⡂⠀ ⠅⠀ ⢃⠀ ⡃⠀ ⠍⠀ ⢋⠀ ⡋⠀ ⠍⠁ ⢋⠁ ⡋⠁ ⠍⠉ ⠋⠉ ⠋⠉ ⠉⠙ ⠉⠙ … (+37) │ 0.08s │ 4.5s │
│ dots13 │ ⣼ ⣹ ⢻ ⠿ ⡟ ⣏ ⣧ ⣶ │ 0.08s │ 2.0s │
│ dots14 │ ⠉⠉ ⠈⠙ ⠀⠹ ⠀⢸ ⠀⣰ ⢀⣠ ⣀⣀ ⣄⡀ ⣆⠀ ⡇⠀ ⠏⠀ ⠋⠁ │ 0.08s │ 2.9s │
│ dots-8bit │ ⠀ ⠁ ⠂ ⠃ ⠄ ⠅ ⠆ ⠇ ⡀ ⡁ ⡂ ⡃ ⡄ ⡅ ⡆ ⡇ ⠈ ⠉ ⠊ ⠋ ⠌ ⠍ ⠎ ⠏ ⡈ ⡉ ⡊ ⡋ … (+228) │ 0.08s │ 20.5s │
│ dots-circle │ ⢎ ⠎⠁ ⠊⠑ ⠈⠱ ⡱ ⢀⡰ ⢄⡠ ⢆⡀ │ 0.08s │ 2.0s │
│ sand │ ⠁ ⠂ ⠄ ⡀ ⡈ ⡐ ⡠ ⣀ ⣁ ⣂ ⣄ ⣌ ⣔ ⣤ ⣥ ⣦ ⣮ ⣶ ⣷ ⣿ ⡿ ⠿ ⢟ ⠟ ⡛ ⠛ ⠫ ⢋ … (+7) │ 0.08s │ 3.0s │
│ line │ - \ | / │ 0.13s │ 2.0s │
│ line2 │ ⠂ - – — – - │ 0.1s │ 2.0s │
│ rolling-line │ / - \ | | \ - / │ 0.08s │ 2.0s │
│ pipe │ ┤ ┘ ┴ └ ├ ┌ ┬ ┐ │ 0.1s │ 2.4s │
│ simple-dots │ . .. ... │ 0.4s │ 3.0s │
│ simple-dots-scrolling │ . .. ... .. . │ 0.2s │ 3.0s │
│ star │ ✶ ✸ ✹ ✺ ✹ ✷ │ 0.07s │ 2.0s │
│ star2 │ + x * │ 0.08s │ 2.0s │
│ flip │ _ _ _ - ` ` ' ´ - _ _ _ │ 0.07s │ 2.5s │
│ hamburger │ ☱ ☲ ☴ │ 0.1s │ 2.0s │
│ grow-vertical │ ▁ ▃ ▄ ▅ ▆ ▇ ▆ ▅ ▄ ▃ │ 0.12s │ 3.0s │
│ grow-horizontal │ ▏ ▎ ▍ ▌ ▋ ▊ ▉ ▊ ▋ ▌ ▍ ▎ │ 0.12s │ 3.0s │
│ balloon │ . o O @ * │ 0.14s │ 2.9s │
│ balloon2 │ . o O ° O o . │ 0.12s │ 2.5s │
│ noise │ ▓ ▒ ░ │ 0.1s │ 2.0s │
│ bounce │ ⠁ ⠂ ⠄ ⠂ │ 0.12s │ 2.0s │
│ box-bounce │ ▖ ▘ ▝ ▗ │ 0.12s │ 2.0s │
│ box-bounce2 │ ▌ ▀ ▐ ▄ │ 0.1s │ 2.0s │
│ triangle │ ◢ ◣ ◤ ◥ │ 0.05s │ 2.0s │
│ binary │ 010010 001100 100101 111010 111101 010111 101011 111000 … (+2) │ 0.08s │ 2.4s │
│ arc │ ◜ ◠ ◝ ◞ ◡ ◟ │ 0.1s │ 2.0s │
│ circle │ ◡ ⊙ ◠ │ 0.12s │ 2.0s │
│ square-corners │ ◰ ◳ ◲ ◱ │ 0.18s │ 2.2s │
│ circle-quarters │ ◴ ◷ ◶ ◵ │ 0.12s │ 2.0s │
│ circle-halves │ ◐ ◓ ◑ ◒ │ 0.05s │ 2.0s │
│ squish │ ╫ ╪ │ 0.1s │ 2.0s │
│ toggle │ ⊶ ⊷ │ 0.25s │ 2.0s │
│ toggle2 │ ▫ ▪ │ 0.08s │ 2.0s │
│ toggle3 │ □ ■ │ 0.12s │ 2.0s │
│ toggle4 │ ■ □ ▪ ▫ │ 0.1s │ 2.0s │
│ toggle5 │ ▮ ▯ │ 0.1s │ 2.0s │
│ toggle6 │ ဝ ၀ │ 0.3s │ 2.0s │
│ toggle7 │ ⦾ ⦿ │ 0.08s │ 2.0s │
│ toggle8 │ ◍ ◌ │ 0.1s │ 2.0s │
│ toggle9 │ ◉ ◎ │ 0.1s │ 2.0s │
│ toggle10 │ ㊂ ㊀ ㊁ │ 0.1s │ 2.0s │
│ toggle11 │ ⧇ ⧆ │ 0.05s │ 2.0s │
│ toggle12 │ ☗ ☖ │ 0.12s │ 2.0s │
│ toggle13 │ = * - │ 0.08s │ 2.0s │
│ arrow │ ← ↖ ↑ ↗ → ↘ ↓ ↙ │ 0.1s │ 2.4s │
│ arrow2 │ ⬆ ↗ ➡ ↘ ⬇ ↙ ⬅ ↖ │ 0.08s │ 2.0s │
│ arrow3 │ ▹▹▹▹▹ ▸▹▹▹▹ ▹▸▹▹▹ ▹▹▸▹▹ ▹▹▹▸▹ ▹▹▹▹▸ │ 0.12s │ 2.2s │
│ bouncing-bar │ [ ] [= ] [== ] [=== ] [====] [ ===] [ ==] [ =] … (+8) │ 0.08s │ 3.0s │
│ bouncing-ball │ ( ● ) ( ● ) ( ● ) ( ● ) ( ●) ( ● ) … (+4) │ 0.08s │ 2.4s │
│ smiley │ 😄 😝 │ 0.2s │ 2.0s │
│ monkey │ 🙈 🙈 🙉 🙊 │ 0.3s │ 3.0s │
│ hearts │ 💛 💙 💜 💚 💗 │ 0.1s │ 2.0s │
│ clock │ 🕛 🕐 🕑 🕒 🕓 🕔 🕕 🕖 🕗 🕘 🕙 🕚 │ 0.1s │ 3.0s │
│ earth │ 🌍 🌎 🌏 │ 0.18s │ 2.0s │
│ material │ █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ … (+90) │ 0.017s │ 3.0s │
│ moon │ 🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘 │ 0.08s │ 2.0s │
│ runner │ 🚶 🏃 │ 0.14s │ 2.0s │
│ pong │ ▐⠂ ▌ ▐⠈ ▌ ▐ ⠂ ▌ ▐ ⠠ ▌ ▐ ⡀ ▌ … (+25) │ 0.08s │ 3.0s │
│ shark │ ▐|\____________▌ ▐_|\___________▌ ▐__|\__________▌ … (+23) │ 0.12s │ 3.1s │
│ dqpb │ d q p b │ 0.1s │ 2.0s │
│ weather │ ☀ ☀ ☀ 🌤 ⛅ 🌥 ☁ 🌧 🌨 🌧 🌨 🌧 🌨 ⛈ 🌨 🌧 🌨 ☁ 🌥 ⛅ … (+3) │ 0.1s │ 3.0s │
│ christmas │ 🌲 🎄 │ 0.4s │ 2.4s │
│ grenade │ ، ′ ´ ‾ ⸌ ⸊ | ⁎ ⁕ ෴ ⁓ │ 0.08s │ 3.0s │
│ point │ ∙∙∙ ●∙∙ ∙●∙ ∙∙● ∙∙∙ │ 0.125s │ 2.0s │
│ layer │ - = ≡ │ 0.15s │ 2.0s │
│ beta-wave │ ρββββββ βρβββββ ββρββββ βββρβββ ββββρββ βββββρβ ββββββρ │ 0.08s │ 2.0s │
│ finger-dance │ 🤘 🤟 🖖 ✋ 🤚 👆 │ 0.16s │ 2.9s │
│ fist-bump │ 🤜 🤛 🤜 🤛 🤜 🤛 🤜 🤛 … (+3) │ 0.08s │ 2.0s │
│ soccer-header │ 🧑⚽ 🧑 🧑 ⚽ 🧑 🧑 ⚽ 🧑 … (+9) │ 0.08s │ 2.9s │
│ mindblown │ 😐 😐 😮 😮 😦 😦 😧 😧 🤯 💥 ✨ │ 0.16s │ 3.0s │
│ speaker │ 🔈 🔉 🔊 🔉 │ 0.16s │ 2.0s │
│ orange-pulse │ 🔸 🔶 🟠 🟠 🔶 │ 0.1s │ 2.0s │
│ blue-pulse │ 🔹 🔷 🔵 🔵 🔷 │ 0.1s │ 2.0s │
│ orange-blue-pulse │ 🔸 🔶 🟠 🟠 🔶 🔹 🔷 🔵 🔵 🔷 │ 0.1s │ 3.0s │
│ aesthetic │ ▰▱▱▱▱▱▱ ▰▰▱▱▱▱▱ ▰▰▰▱▱▱▱ ▰▰▰▰▱▱▱ ▰▰▰▰▰▱▱ ▰▰▰▰▰▰▱ ▰▰▰▰▰▰▰ … (+1) │ 0.08s │ 2.0s │
│ dwarf-fortress │ ██████£££ ☺██████£££ ☺██████£££ ☺▓█████£££ … (+129) │ 0.08s │ 10.6s │
│ fish │ ~~~~~~~~~~~~~~~~~~~~ > ~~~~~~~~~~~~~~~~~~ … (+25) │ 0.08s │ 3.0s │
╰───────────────────────┴──────────────────────────────────────────────────────────────────┴──────────┴───────╯
Every one of them, animating:
Name |
Animation |
Name |
Animation |
Name |
Animation |
|---|---|---|---|---|---|
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|
Bell on completion¶
Set beep=True to ring the terminal bell once when the spinner stops, handy for a long task you walk away from. It rings only when the spinner was actually shown, so redirected or non-interactive runs stay quiet:
with Spinner("Baking bread", beep=True):
sleep(5)
Printing while spinning¶
Because the spinner draws to stderr, results written to stdout never collide with the animation. To emit a line on the same stream as the spinner, use echo(): it erases the current frame, prints the message above the spinner, and lets the animation carry on underneath. A bare print would instead leave a frame glyph stranded mid-line.
from time import sleep
from click_extra import Spinner
def pick(stream=None):
"""Fill three baskets, tracing each one as it lands."""
with Spinner("Picking apples", stream=stream) as spinner:
for basket in range(3):
sleep(1.5)
spinner.echo(f"Filled basket {basket}")
The stream argument is threaded through only so this page can record the animation below. A real call leaves it out, and the spinner finds stderr on its own.
Each echoed line is kept where it landed and the animation carries on below it, which is the whole difference from a bare print.
Parallel work¶
A Spinner drives a single line, and one spinner can report on a whole pool of concurrent tasks. The simplest way is to let the main thread update it as the tasks finish, through concurrent.futures.as_completed.
Update the label for a running count:
from concurrent.futures import ThreadPoolExecutor, as_completed
cities = ["Cairo", "Lima", "Oslo", "Paris", "Tokyo"]
# How long each forecast takes to come back, standing in for a real fetch.
latency = {"Cairo": 1.7, "Lima": 0.5, "Oslo": 2.1, "Paris": 0.9, "Tokyo": 1.3}
def fetch(city):
sleep(latency[city]) # The blocking call: a download, a query, a subprocess.
return city
def count_forecasts(stream=None):
"""Fetch every forecast at once, counting them off as they land."""
with Spinner(f"Fetching forecasts (0/{len(cities)})", stream=stream) as spinner:
with ThreadPoolExecutor() as pool:
futures = [pool.submit(fetch, city) for city in cities]
for done, _ in enumerate(as_completed(futures), 1):
spinner.label = f"Fetching forecasts ({done}/{len(cities)})"
# A spinner erases itself on the way out, so the final tally only
# reaches the screen if the animation gets one more beat to draw it.
sleep(0.3)
Or echo() a line as each task lands, leaving a trail of finished work that scrolls up while the spinner keeps turning below it:
def trail_forecasts(stream=None):
"""Fetch every forecast at once, leaving a line behind for each."""
with Spinner("Fetching forecasts", stream=stream) as spinner:
with ThreadPoolExecutor() as pool:
futures = {pool.submit(fetch, city): city for city in cities}
for future in as_completed(futures):
spinner.echo(f"✓ {futures[future]}")
The cities land in whatever order the pool finishes them, which is why the trail above is not alphabetical.
Both label and echo() are safe to touch while the animation runs, so a worker thread can stream its own progress mid-task rather than only reporting on completion. A genuine spinner per task, several rotating at once on their own lines, is a separate capability: it needs a coordinated multi-line region, which Spinner does not attempt.
The operation trail¶
The two idioms above (a running done/total label, plus one echoed line per finished task) are packaged together as OperationTrail, the batch-reporting companion of the concurrency primitives run_jobs and run_lanes. Each completed operation leaves a persistent ✓, ✘ or ⊘ trail_line() on screen, and finish() closes the batch with a kept summary line:
from click_extra.jobs import run_jobs
from click_extra.trail import OperationTrail
jobs = 4
with OperationTrail(
label="Fetching", unit="feeds", total=len(feeds), jobs=jobs
) as trail:
def fetch(feed):
trail.mark(*pull(feed)) # pull() returns (ok, message).
list(run_jobs(fetch, feeds, jobs=jobs))
trail.finish(
trail.ok_count == len(feeds),
f"Fetched {trail.ok_count}/{len(feeds)} feeds",
)
Run concurrently, that is one aggregate spinner carrying the tally while the finished operations stack up above it:
The rendering adapts to the batch’s concurrency, and you pick neither mode by hand. Run concurrently (jobs > 1), one aggregate spinner carries the Fetching 3/5 feeds tally while the trail lines stream above it, its animation picked from the catalog with spinner=SPINNERS["moon"]. Run sequentially (jobs <= 1), each outcome echoes as a plain line and every operation stays free to keep its own per-call Spinner. Either way the finisher carries the elapsed time. OperationTrail details what each mode drives.
Only the aggregate spinner or bar needs an interactive terminal, since it redraws in place. The trail lines and the finisher print on any stream, so a pipe or a CI log keeps the batch’s record, and mark() is safe to call from worker threads. A sequential batch whose real product is another output (a result table on stdout) can silence its trail with echo_sequential=False while keeping the ok_count tally.
Two arguments decide what a trail shows. live says where its spinner or bar may draw: "auto" (the default) on an interactive terminal, unless --no-progress or --accessible turned progress off; "always" on any stream; and "never" nowhere. A trail that does not draw keeps its lines. visible=False silences the whole trail.
This page captures its commands off a terminal, and the trail still prints there. That is how it shows a live sequential run:
from click_extra import command
from click_extra.trail import OperationTrail
@command
def roast():
"""Roast a tray of vegetables, tracing each outcome as it lands."""
vegetables = ["carrots", "fennel", "leeks", "peppers"]
with OperationTrail(jobs=1) as trail:
for vegetable in vegetables:
roasted = vegetable != "leeks" # The leeks caught the heat.
trail.mark(
roasted,
f"{vegetable} roasted" if roasted else f"{vegetable} scorched",
)
trail.finish(
trail.ok_count == len(vegetables),
f"Roasted {trail.ok_count}/{len(vegetables)} vegetables",
)
$ roast
✓ carrots roasted
✓ fennel roasted
✘ leeks scorched
✓ peppers roasted
✘ Roasted 3/4 vegetables
The lines echo in order as each outcome lands, and the run closes on the ✘ finisher because one vegetable scorched: the same trail a sequential batch leaves in a real terminal, without the live redraw.
The trail’s timer follows the --time / --no-time flag by default (timer=None), so this untimed run shows no clocks. Under --time the ✘ finisher gains the batch’s total, and each operation can report its own elapsed time: wrap the work in an operation() handle, whose mark() times itself, so the lines read ✓ carrots roasted (2.4s). Force it either way with timer=True or timer=False, or hand timer a lambda seconds: … callable to format the clock.
def roast(vegetable):
op = trail.operation() # Start this operation's clock.
roasted = vegetable != "leeks"
op.mark(
roasted,
f"{vegetable} roasted" if roasted else f"{vegetable} scorched",
)
While the batch runs, the aggregate indicator counts the elapsed time up from zero by default; pass clock="eta" to count down an estimate of the time remaining instead. A determinate bar reads that estimate from Click natively, and the concurrent spinner borrows the same click.progressbar estimator since the trail knows its total. The per-operation and finisher times stay elapsed either way.
The bundled CLI wraps all three renderings in one command, to watch in a terminal what this page can only echo: click-extra trail roasts a batch behind a concurrent aggregate spinner, --jobs 1 drops to the sequential plain-line trail above, and --progress-bar swaps the spinner for a determinate bar.
$ click-extra trail --help
Usage: click-extra trail [OPTIONS]
Trace a simulated batch of operations behind an operation trail.
Roasts a handful of make-believe vegetables (each a short pause, the leeks
scorching) and reports them as they land. The display follows the batch: with
--jobs 1 each outcome echoes as a plain line; with two or more jobs a spinner
carries the running tally while outcomes stream above it; --progress-bar swaps
that spinner for a determinate progress bar. Add --time to append each
vegetable's roast time and the batch total; --elapsed and --eta turn that on
too, counting up from zero or down as an estimate. Under --no-progress, or off
an interactive terminal, no spinner or bar draws, and each outcome and the
summary print as plain lines.
Options:
--progress-bar Drive the batch with a determinate progress bar
instead of a spinner.
--eta / --elapsed For --progress-bar, show the time remaining (--eta)
or elapsed (--elapsed); either one turns timing on,
like --time. A spinner always shows elapsed time.
--spinner NAME Aggregate spinner animation for concurrent runs
(see the spinner command for names). Defaults to
the built-in spinner; ignored with --progress-bar.
--jobs [auto|max|INTEGER] Number of parallel jobs. Accepts an integer, auto
(the host's logical CPUs, minus one when there are
three or more) or max (all logical CPUs). --jobs 0
runs sequentially. [default: auto]
-h, --help Show this message and exit.
A Ctrl+C inside the trail still ends it on a finisher, like ✘ Interrupted after 2/5 roasts, so the record of the batch says where it stopped. A task already running when the Ctrl+C landed prints its own outcome below that line once it finishes, while the CLI waits for it.
Skipped operations¶
An operation that neither succeeded nor failed, like one with nothing to do, marks None instead of a boolean. Its line takes the ⊘ glyph of SKIP_GLYPH, painted with the theme’s warning style, and skip_count tallies it apart from ok_count, so the finisher can leave it out of its count:
from click_extra import command
from click_extra.trail import OperationTrail
@command
def harvest():
"""Pick the orchard's fruits, skipping the ones out of season."""
fruits = {"apples": True, "cherries": None, "pears": True}
with OperationTrail(jobs=1) as trail:
for fruit, in_season in fruits.items():
trail.mark(in_season, f"{fruit} picked" if in_season
else f"{fruit} out of season")
picked = trail.ok_count
tried = len(fruits) - trail.skip_count
trail.finish(
picked == tried,
f"Picked {picked}/{tried} fruits, {trail.skip_count} skipped",
)
$ harvest
✓ apples picked
⊘ cherries out of season
✓ pears picked
✓ Picked 2/2 fruits, 1 skipped
finish() takes None too, for a batch that skipped every operation. Outside a trail, trail_glyph() draws the same glyph for None, and Spinner.skip() leaves it on a kept line, like ok() and fail() do below.
A progress bar instead of a spinner¶
Because the trail knows its total, it can carry a determinate progress bar rather than an indeterminate spinner. Give the roast command above a bar by adding progress_bar=True (mutually exclusive with spinner=, and requiring a positive total), plus the label and unit its tally reads:
with OperationTrail(
label="Roasting",
unit="vegetables",
total=len(vegetables),
progress_bar=True,
) as trail:
... # mark() each outcome, then finish(), exactly as above.
The aggregate indicator becomes a bar holding the done/total count, the same outcome lines streaming above it, and a kept summary replaces the bar on finish(). It serves sequential and concurrent batches alike.
Unlike the sequential trail above, the bar is driven by cursor-control codes, so it draws only on an interactive terminal, unless live="always" forces it. Recorded off one, the landed outcomes sit above a bar tracking the tally:
When the last vegetable lands, finish() replaces the bar with the kept ✘ Roasted 3/4 vegetables (0.0s) summary, the same trail a sequential run leaves behind. A log record emitted mid-batch still lands on its own line above the bar, through the same cooperation the spinner uses. To watch a bar drive a live batch, run click-extra trail --progress-bar in a terminal.
Styling and color¶
The spinner’s glyph, label and timer are painted with a Style instance: the very type Click Extra’s theme system is built on. The simplest customization is a foreground color:
from click_extra import Spinner, Style
with Spinner("Counting sheep", style=Style(fg="cyan")):
sleep(5)
A Style carries far more than a foreground color. Add a background with bg, and text attributes like bold, dim, italic, underline, blink or reverse, and combine them freely:
with Spinner("Counting sheep", style=Style(fg="bright_white", bg="blue", bold=True)):
sleep(5)
Colors accept any form click.style understands: ANSI names ("red", "bright_magenta"), 256-color indexes, #rrggbb hex strings, or (r, g, b) tuples. A Style carrying an unrenderable color or attribute is rejected with a ValueError at construction, so a typo fails fast instead of silently dying on the animation thread.
Color follows the terminal, not the spinner¶
Color is decoupled from the animation: under --no-color or NO_COLOR the spinner keeps spinning, just in plain text (the --progress section below explains the rationale). Inside a Click Extra CLI the color follows the reconciled --color/--no-color flag; standalone it reads the same environment variables as --color, then falls back to whether the terminal is interactive.
The same Style type colors the ok(), fail() and skip() finishers: they default to the theme’s success, error and warning style and take a style= override, covered in the Success and failure section below.
Success and failure¶
Stopping the spinner (or leaving its context) erases it and shows the cursor it hid, even when SIGTERM kills the process, which runs no clean-up of its own. To leave a result on screen instead, finish with ok() or fail(): each replaces the final frame with a kept line. The marker defaults to the theme’s success/error glyph (✓ / ✘), painted with the active theme’s success/error Style, so a finished spinner matches the rest of a themed CLI.
with Spinner("Baking bread") as spinner:
sleep(5)
spinner.ok() # ✓ Baking bread
A call that had nothing to do can finish with skip() instead, whose ⊘ marker takes the theme’s warning style. Pass your own marker (spinner.ok("done")) or override the paint with a Style (spinner.fail(style=Style(fg="bright_red"))). Color is stripped under --no-color/NO_COLOR; off a terminal the line is still written, so the outcome is recorded in logs and pipes.
Because the finisher is written even when the spinner never appeared (a call shorter than the delay, a pipe, a non-terminal), gate it on the shown property when you only want it after a spinner the reader actually saw:
with Spinner("Baking bread") as spinner:
bake()
if spinner.shown:
spinner.ok()
Elapsed time¶
Set timer=True to append the running wall-clock time to the spinner, and to any ok(), fail() or skip() line:
with Spinner("Simmering stock", timer=True) as spinner:
sleep(5)
spinner.ok() # ✓ Simmering stock (5.0s)
The default format is compact: 2.3s, then 1:05, then 1:02:03. For anything else, pass a callable instead of True: it receives the elapsed seconds and returns the string to show:
with Spinner("Simmering stock", timer=lambda s: f"{s / 60:.0f} min") as spinner:
sleep(5)
spinner.ok() # ✓ Simmering stock (0 min)
Read the elapsed time any moment from the elapsed_time property, which freezes once the spinner stops.
The --progress option¶
click_extra.command and click_extra.group add a --progress/--no-progress flag to every CLI by default. It resolves to a single boolean at ctx.meta["click_extra.progress"]. A Spinner or an OperationTrail left at live="auto" reads it on its own, so --no-progress keeps it from drawing with no wiring in the command:
from click_extra import Spinner, command
@command
def harvest():
"""Pick apples behind a spinner, unless --no-progress is passed."""
with Spinner("Picking apples"):
sleep(5)
Pass live="always" or live="never" to decide regardless of the flag.
A command that is not a Click Extra one gets the same flag from the @progress_option decorator:
import click
from click_extra import Spinner, progress_option
@click.command
@progress_option
def press():
"""Press apples into cider."""
with Spinner("Pressing apples"):
click.echo("Cider is ready.")
$ press --help
Usage: press [OPTIONS]
Press apples into cider.
Options:
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible.
--help Show this message and exit.
Spinner display is decoupled from color. A spinner is an interactivity concern, not a color one: it is driven by cursor-control codes, which the NO_COLOR standard explicitly does not govern. So --no-color and NO_COLOR strip the spinner’s color but keep it spinning, the same way cargo, npm, pip, Rich, indicatif and ora gate progress on the terminal rather than on color.
The resolved value is False only for non-interactive output (a pipe, a TERM=dumb terminal, or CI: handled by the widget’s own check when you pass live="auto") and for explicit intent (--no-progress or --accessible, the latter so a screen reader is never handed a spinning glyph).
Progress bars¶
The same --progress/--no-progress flag also gates Click’s determinate progress bar. click_extra.progressbar is a drop-in for click.progressbar: it reads the resolved flag and hides the bar when progress is off, so a single --no-progress (or --accessible) silences both the indeterminate spinner and the determinate bar.
from click_extra import command, progressbar
@command
def harvest():
"""Pick apples behind a determinate progress bar."""
with progressbar((1, 2, 3), label="Picking apples") as bar:
for _ in bar:
pass
$ harvest
Picking apples
$ harvest --no-progress
The hidden argument stays authoritative: pass an explicit hidden=True or hidden=False to force the bar regardless of the flag, mirroring how an explicit color= overrides ctx.color on click.echo. Color is handled upstream too, since Click renders the bar through click.echo: --no-color and NO_COLOR strip its ANSI without any extra wiring.
The bar’s estimated-time display is gated the same way, but on --time rather than --progress: show_eta defaults to None, shown under --time and hidden otherwise, so a bare bar and an operation trail agree on when to surface timing. An explicit show_eta=True or show_eta=False overrides it (Click’s own default is True).
Three more defaults set the bar apart from Click’s:
It draws on stderr, like a spinner and a trail, unless
filenames another stream. That keeps stdout free for the data a command prints.A record logged while the bar draws prints on a line of its own above the bar, which then draws again below it. Click draws a bar with a carriage return and no line feed until it finishes, so its own bar leaves a record on the bar’s row, after its position.
The bar redraws at most once every 0.1 seconds, the cadence of a spinner’s frames, so a bar over 20,000 fast items does not write to the terminal 20,000 times, and a bar over slow items still moves with each of them. Its position moves on every step. An explicit
update_min_stepskeeps Click’s own gate on a count of items.