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
Spinnergiven 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
Spinnercurrently animating, orNone.A spinner-typed view of
_active_line(), skipping any progress-bar indicator that may own the line instead. Withstreamgiven, only a spinner drawing on that very stream matches.
- 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_GLYPHpainted with the active theme’ssuccessslot, the failure glyphKO_GLYPHpainted with itserrorslot, or the skip glyphSKIP_GLYPHpainted with itswarningslot.- Parameters:
ok (
bool|None) – whether the outcome is a success, orNonefor 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:
- 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:
objectA 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 callingstop()) halts the thread and erases the spinner line so it never lingers above the next output.Note
A single
Spinnerinstance drives one animation at a time. A tool running its steps one after another can share one instance and reassign itslabelbetween 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@Spinnerdecorator 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 toSPINNER_FRAMES, or thespinnerpreset’s frames when given.spinner (
SpinnerPreset|None) – aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicitframesorintervalstill 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 customframes.interval (
float|None) – seconds between two frames. Defaults toDEFAULT_INTERVAL, or thespinnerpreset’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) – aStyleapplied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation:--no-color/NO_COLORstrip it while the spinner keeps spinning (seeProgressOption). The strip reaches escapes embedded inlabelitself too, so a label styled by hand is as safe as one styled through these arguments.label_style (
Style|None) – aStylefor the label alone, in place ofstylethere. It also paints the label of the keptok()/fail()line, whichstyleleaves plain. It outlives a reassignedlabel, 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 finalok()/fail()line.None(the default) follows the CLI’s--time/--no-timeflag, as anOperationTraildoes.Trueforces it on withformat_duration()’s compact format (2.3s,1:05, then1:02:03),Falseforces it off, and a callable(seconds: float) -> strformats the duration yourself, liketimer=lambda s: f"{s / 60:.0f}m"for whole minutes.timer_style (
Style|None) – aStylefor the timer, parentheses included, in place ofstylethere (Style(dim=True)to set the clock back from the label). Atimercallable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the keptok()/fail()line.stream (
IO[str] |None) – where to draw; defaults tosys.stderrso the spinner never mixes intostdoutdata.live (
Literal['auto','always','never']) – where the animation may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns it off,"always"on any stream,"never"nowhere. A spinner that does not draw still writes itsok()/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_styleortimer_stylecarries a color or attribute that cannot be rendered, or ifliveis not one ofWHEN.
- 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 oncestop()is called.Returns
0.0before the spinner has started.
- property shown: bool¶
Whether the spinner has drawn at least one frame to its stream.
Trueonly once an animation frame was actually rendered. It staysFalsefor a disabled spinner (off a TTY, on aTERM=dumbterminal, or withlive="never") and for a call that finishes withindelay, before the first frame. Reset bystart().Use it to gate output that should mirror the spinner’s visibility.
ok()andfail()write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them withshownwhen 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 waystart()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.
- 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 laterok()/fail()can report a duration).- Return type:
- 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:
- echo(message='')[source]¶
Print
messageon its own line above the running spinner.Click’s
click.progressbar()and a bareprintboth 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, writesmessagefollowed 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(stderrby default), so results written tostdoutnever need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write ofmessagewith no control codes.- Return type:
- 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 withsymbolfollowed by the current label (and the elapsed time whentimeris set), then keeps that line.symboldefaults to the themed success glyphOK_GLYPH(✓), painted with the active theme’ssuccessslot unlessstyleoverrides it. Color is stripped under--no-color/NO_COLOR; the glyph stays.- Return type:
- fail(symbol=None, *, style=None)[source]¶
Stop the spinner and leave a persistent failure line on screen.
The failure counterpart of
ok(), defaulting toKO_GLYPH(✘) painted with the active theme’serrorslot.- Return type:
- 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 toSKIP_GLYPH(⊘) painted with the active theme’swarningslot.- Return type:
- 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:
ExtraOptionA pre-configured
--progress/--no-progressflag gating spinner display.Resolves to a single boolean published at
ctx.meta[click_extra.context.PROGRESS], whichSpinner,OperationTrailandprogressbar()read on their own when left at their automatic default. The default isTrue;--accessiblelowers it toFalse(viadefault_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_COLORstrip 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/--quietknob), whileNO_COLORonly affects color. Rich takesTERM=dumb, notNO_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=dumbterminal that cannot move the cursor (see_can_draw());explicit intent:
--no-progressor--accessible.
This option is eager. It never reads
ctx.color, so its position relative toColorOptiondoes not matter.- set_progress(ctx, param, value)[source]¶
Publish whether progress spinners may be shown.
Stores the resolved
--progressflag atPROGRESS. Deliberately independent of color: see theProgressOptionnote for why a spinner is gated on interactivity (TTY /TERM=dumb) and--accessible, never on--no-color/NO_COLOR.- Return type: