click_extra.spinner module

        classDiagram
  ExtraOption <|-- ProgressOption
  tuple <|-- SpinnerPreset
    

An indeterminate terminal spinner for long-running, blocking work.

Click ships click.progressbar(), but it is determinate: it needs a known length or an iterable to advance through. Some work has no measurable progress: a blocking subprocess, a network round-trip, a query whose duration is unknown. For those, the only honest feedback is “something is happening”.

Spinner fills that gap. It animates a small frame sequence on a daemon thread, so the caller can stay blocked in a single call (communicate(), urlopen(), …) while the spinner keeps turning:

from time import sleep

from click_extra import Spinner

with Spinner("Brewing tea"):
    sleep(5)  # A blocking call with no measurable progress.

This module also keeps the registry of the live lines drawing on the terminal, which OperationTrail and progressbar() join while they draw.

Caution

The spinner draws with carriage returns and ANSI control codes, so it is a no-op whenever its output stream is not a TTY (a pipe, a file, a captured test buffer, a CI log), unless live="always" forces it. This keeps redirected output and machine-readable formats clean.

Note

On Windows, Spinner.start() enables the console’s virtual-terminal processing so the ANSI control codes animate in place rather than print literally (⠋␛[0m … ␛[K). Modern terminals (Windows Terminal, recent conhost) already have it on; this just covers older consoles.

click_extra.spinner.CLEAR_LINE: Final = '\x1b[K'

Erase the line from the cursor to its end.

Written after a carriage return, it clears the row a live line is about to redraw, so a shrinking label leaves no stale characters behind.

click_extra.spinner.HIDE_CURSOR: Final = '\x1b[?25l'

Hide the terminal’s cursor, which would otherwise flicker beside a live line.

click_extra.spinner.SHOW_CURSOR: Final = '\x1b[?25h'

Show the cursor again, once a live line stops drawing.

click_extra.spinner.DEFAULT_INTERVAL: Final = 0.1

Seconds between two frames of a Spinner given no other cadence.

Also how often a progress bar carrying a running clock redraws, so the two live lines tick at the same rate.

click_extra.spinner.active_spinner(stream=None)[source]

Return the innermost Spinner currently animating, or None.

A spinner-typed view of _active_line(), skipping any progress-bar indicator that may own the line instead. With stream given, only a spinner drawing on that very stream matches.

Return type:

Spinner | None

click_extra.spinner.trail_glyph(ok, symbol=None, style=None, *, color=True)[source]

Return the ✓, ✘ or ⊘ glyph marking an outcome, painted for it.

The success glyph OK_GLYPH painted with the active theme’s success slot, the failure glyph KO_GLYPH painted with its error slot, or the skip glyph SKIP_GLYPH painted with its warning slot.

Parameters:
  • ok (bool | None) – whether the outcome is a success, or None for an operation that was skipped: it neither succeeded nor failed.

  • symbol (str | None) – a glyph to draw in place of the themed one.

  • style (Style | None) – a style to paint the glyph with, in place of the theme’s slot.

  • color (bool) – whether to paint the glyph at all. With color off, the glyph goes bare and the theme is never consulted.

Return type:

str

Returns:

the glyph, painted or bare.

class click_extra.spinner.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, label_style=None, timer=None, timer_style=None, stream=None, live='auto', hide_cursor=True, beep=False)[source]

Bases: object

A thread-animated, indeterminate progress spinner usable as a context manager.

The animation runs on a background daemon thread, leaving the calling thread free to block on the actual work. Entering the context (or calling start()) begins the animation; leaving it (or calling stop()) halts the thread and erases the spinner line so it never lingers above the next output.

Note

A single Spinner instance drives one animation at a time. A tool running its steps one after another can share one instance and reassign its label between steps. Concurrent work takes one instance per thread.

Configure (but do not start) the spinner.

Parameters:
  • label (str | Callable[..., Any]) – text shown after the spinner glyph. As a special case, a bare @Spinner decorator passes the wrapped function here instead; it is detected and the label defaults to empty.

  • frames (Sequence[str] | None) – the animation frames, cycled in order. Defaults to SPINNER_FRAMES, or the spinner preset’s frames when given.

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicit frames or interval still overrides it.

  • reverse (bool) – cycle the frames backwards, spinning the animation the other way. Set it when the rotation runs counter to what you expect; it composes with any custom frames.

  • interval (float | None) – seconds between two frames. Defaults to DEFAULT_INTERVAL, or the spinner preset’s interval when given.

  • delay (float) – seconds to wait before drawing the first frame. A non-zero delay keeps the spinner silent for calls that finish quickly, so it only surfaces once an operation is genuinely slow.

  • style (Style | None) – a Style applied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation: --no-color / NO_COLOR strip it while the spinner keeps spinning (see ProgressOption). The strip reaches escapes embedded in label itself too, so a label styled by hand is as safe as one styled through these arguments.

  • label_style (Style | None) – a Style for the label alone, in place of style there. It also paints the label of the kept ok() / fail() line, which style leaves plain. It outlives a reassigned label, where styling embedded in the text has to be applied again at every step.

  • timer (bool | Callable[[float], str] | None) – append the elapsed wall-clock time to the spinner, and to any final ok() / fail() line. None (the default) follows the CLI’s --time / --no-time flag, as an OperationTrail does. True forces it on with format_duration()’s compact format (2.3s, 1:05, then 1:02:03), False forces it off, and a callable (seconds: float) -> str formats the duration yourself, like timer=lambda s: f"{s / 60:.0f}m" for whole minutes.

  • timer_style (Style | None) – a Style for the timer, parentheses included, in place of style there (Style(dim=True) to set the clock back from the label). A timer callable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the kept ok() / fail() line.

  • stream (IO[str] | None) – where to draw; defaults to sys.stderr so the spinner never mixes into stdout data.

  • live (Literal['auto', 'always', 'never']) – where the animation may draw: "auto" (the default) on an interactive terminal only, unless --no-progress turns it off, "always" on any stream, "never" nowhere. A spinner that does not draw still writes its ok() / fail() line.

  • hide_cursor (bool) – hide the text cursor while spinning and restore it on stop.

  • beep (bool) – ring the terminal bell once when the spinner stops. It fires only when the spinner was active, so a disabled or redirected spinner stays silent.

Raises:

ValueError – if style, label_style or timer_style carries a color or attribute that cannot be rendered, or if live is not one of WHEN.

label: str

Text drawn after the spinner glyph.

Reassign it at any time while the spinner runs to reflect the current step; the animation thread reads it afresh on every frame.

property elapsed_time: float

Seconds elapsed since start(), frozen once stop() is called.

Returns 0.0 before the spinner has started.

property shown: bool

Whether the spinner has drawn at least one frame to its stream.

True only once an animation frame was actually rendered. It stays False for a disabled spinner (off a TTY, on a TERM=dumb terminal, or with live="never") and for a call that finishes within delay, before the first frame. Reset by start().

Use it to gate output that should mirror the spinner’s visibility. ok() and fail() write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them with shown when you only want the finisher on screen after a spinner the user actually saw:

with Spinner("Baking bread") as spinner:
    bake()
    if spinner.shown:
        spinner.ok()
frame_lines(*, color=True)[source]

Every line this spinner’s animation draws, one per frame.

One turn of the animation, held still. reverse, the label, the style and the timer all land the way start() would draw them, which is what an animated capture stacks into a picture of this spinner.

Note

The timer is read once, here, so every line carries the same elapsed time rather than a counting one: a still cannot show a clock running. A spinner that never started reads zero.

Parameters:

color (bool) – style each line. On by default, because a capture renders ANSI whatever the terminal the spinner would have drawn on accepts.

Return type:

tuple[str, ...]

Returns:

the lines, in the order the animation cycles them.

start()[source]

Begin animating on a background thread, unless the spinner is disabled.

A disabled spinner (non-TTY stream, or live="never") returns at once without spawning a thread or emitting anything (but still records the start time, so a later ok() / fail() can report a duration).

Return type:

None

stop()[source]

Halt the animation and erase the spinner line.

Idempotent and safe to call when the spinner never started. Restores the cursor and clears the line only if the animation actually drew to the terminal.

Return type:

None

echo(message='')[source]

Print message on its own line above the running spinner.

Click’s click.progressbar() and a bare print both fight the animation: a frame drawn between the cursor returns and the text mangles the line. echo() takes the same draw lock as the animation thread, erases the in-progress frame, writes message followed by a newline, and lets the next tick redraw the spinner underneath. It is safe to call from another thread while the spinner runs.

Output goes to the spinner’s own stream (stderr by default), so results written to stdout never need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write of message with no control codes.

Return type:

None

ok(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent success line on screen.

Where stop() erases the spinner, ok() replaces the final frame with symbol followed by the current label (and the elapsed time when timer is set), then keeps that line. symbol defaults to the themed success glyph OK_GLYPH (✓), painted with the active theme’s success slot unless style overrides it. Color is stripped under --no-color / NO_COLOR; the glyph stays.

Return type:

None

fail(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent failure line on screen.

The failure counterpart of ok(), defaulting to KO_GLYPH (✘) painted with the active theme’s error slot.

Return type:

None

skip(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent line for a skipped call.

The counterpart of ok() for a call that neither succeeded nor failed, defaulting to SKIP_GLYPH (⊘) painted with the active theme’s warning slot.

Return type:

None

class click_extra.spinner.ProgressOption(param_decls=None, *, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --progress/--no-progress flag gating spinner display.

Resolves to a single boolean published at ctx.meta[click_extra.context.PROGRESS], which Spinner, OperationTrail and progressbar() read on their own when left at their automatic default. The default is True; --accessible lowers it to False (via default_map) so a screen reader is never handed a spinning glyph.

Note

Spinner display is decoupled from color, even though both emit ANSI. A spinner is an interactivity concern, not a color one: it is built from cursor-control codes (hide-cursor, carriage return, clear-line), which the NO_COLOR standard does not govern. It “only signals the user’s intention regarding adding ANSI color to text output”. So --no-color / NO_COLOR strip the spinner’s colors but never hide it.

The wider ecosystem treats the two axes the same way: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated --progress/--quiet knob), while NO_COLOR only affects color. Rich takes TERM=dumb, not NO_COLOR, as the signal to drop cursor-moving features like progress bars.

Two things silence the spinner, neither of them color:

  • non-interactive output: a pipe, file, CI log, or TERM=dumb terminal that cannot move the cursor (see _can_draw());

  • explicit intent: --no-progress or --accessible.

This option is eager. It never reads ctx.color, so its position relative to ColorOption does not matter.

set_progress(ctx, param, value)[source]

Publish whether progress spinners may be shown.

Stores the resolved --progress flag at PROGRESS. Deliberately independent of color: see the ProgressOption note for why a spinner is gated on interactivity (TTY / TERM=dumb) and --accessible, never on --no-color / NO_COLOR.

Return type:

None