click_extra.trail module¶
A ✓/✘ progress trail that reports a batch of operations.
OperationTrail leaves a persistent trail_line() for each completed
operation, keeps a running done/total tally on an aggregate indicator while the
batch runs, and closes the batch with a kept summary line. The indicator is a
Spinner or a determinate click.progressbar().
- click_extra.trail.trail_line(ok, message)[source]¶
Format one trail line: the glyph of the outcome followed by
message.The glyph is the one
trail_glyph()paints:✓for a success,✘for a failure, and⊘forNone, an operation that was skipped.- Return type:
- class click_extra.trail.OperationTrail(*, label='', unit='', total=0, jobs=1, spinner=None, progress_bar=False, timer=None, clock='elapsed', visible=True, live='auto', echo_sequential=True, delay=0.0, stream=None)[source]¶
Bases:
objectA
✓/✘progress trail and finisher for a batch of operations.Where
Spinnernarrates one long-running call,OperationTrailreports a batch of them: each completed operation leaves a persistenttrail_line()on screen, a runningdone/totaltally keeps the batch’s pulse visible, andfinish()closes with a persistent summary line. The natural reporting companion of the concurrency primitivesrun_jobs()andrun_lanes(), rendered one of three ways:sequential (
jobs <= 1): echo each outcome as it lands, with no aggregate indicator (each operation is free to keep its own per-callSpinner).finish()appends the elapsed time.concurrent (
jobs > 1): drive one aggregateSpinner(per-call spinners would collide on the shared stream), buffering outcomes until it first draws, then streaming the rest live above it. Pick the animation from theSPINNERScatalog withspinner=.progress bar (
progress_bar=True): drive one aggregate determinate bar carrying the{done}/{total}tally, with outcomes streaming above it. Serves sequential and concurrent batches alike, and needs a knowntotal.
The aggregate indicators redraw in place, which a pipe or a CI log cannot do, so by default they draw only on an interactive terminal, and
livechanges where they draw. The✓/✘lines and the finisher only append, so they print on any stream, in plain text where color is off. Where no indicator draws, every rendering echoes each outcome as it lands, as the sequential one does.visible=Falsesilences all of it. The running✓tally is kept as outcomes land (ok_count), so a caller computes no counts of its own.An operation that neither succeeded nor failed, like one with nothing to do, marks
None: its line takes the⊘glyph ofSKIP_GLYPH, andskip_counttallies it apart fromok_count, so a finisher can leave it out of its count.Thread-safe:
mark()may be called from worker threads. Use it as a context manager whenever it may run concurrently, to bound the aggregate spinner’s life; a purely sequential caller may construct it bare.from click_extra.jobs import run_jobs from click_extra.trail import OperationTrail 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", )
Configure (but do not start) the trail.
- Parameters:
label (
str) – present-tense verb for the running aggregate indicator ("Fetching"), composed into its{label} {done}/{total} {unit}tally.unit (
str) – the noun counted in the tally ("files","feeds").total (
int) – how many outcomes are expected, for thedone/totalcount.jobs (
int) – the batch’s worker count;> 1selects the concurrent rendering (one aggregate spinner),<= 1the sequential one (plain echoed lines).spinner (
SpinnerPreset|None) – aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]) for the concurrent aggregate spinner. Ignored by the sequential and progress-bar renderings, and mutually exclusive withprogress_bar.progress_bar (
bool) – render the aggregate indicator as a determinateclick.progressbar()instead of a spinner, for a sequential or concurrent batch alike. Requires a positivetotal(a bar needs a length) and is mutually exclusive withspinner.timer (
bool|Callable[[float],str] |None) – append each operation’s and the batch’s elapsed time to the trail lines and the finisher.None(the default) follows the CLI’s--time/--no-timeflag;Trueforces timing on withformat_duration()’s compact clock, a callable(seconds: float) -> strforces it on with a custom format, andFalseforces it off. Per-operation times come from asecondsargument tomark(), filled in automatically by anoperation()handle.clock (
Literal['elapsed','eta']) – whether a running aggregate indicator shows elapsed time ("elapsed", the default: a stopwatch counting up, visible from the start) or remaining time ("eta": an estimate from the batch’s rate, appearing only once an outcome lets it be computed). Both the progress bar and the concurrent spinner honor"eta"(the spinner reuses Click’s progress-bar estimate, since the trail knows itstotal). Per-operation and finisher times are always elapsed.visible (
bool) – whether the trail shows anything.Falsesilences the lines, the finisher and the aggregate indicator, whileok_countkeeps counting.live (
Literal['auto','always','never']) – where the aggregate indicator may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns it off,"always"on any stream,"never"nowhere. Where it does not draw, each outcome line prints as it lands.echo_sequential (
bool) – whether the batch echoes its outcome lines and finisher as plain lines at all: in a sequential batch, in a batch whose aggregate indicator cannot draw on the stream, and in one that finishes before its indicator first draws. Turn it off when the batch has another output that is the real product (a result table) and the trail would be noise. An indicator that did draw is unaffected.delay (
float) – seconds before the aggregate indicator first draws: a fast batch then completes without ever flashing one, its lines echoed plainly atfinish()instead (seeecho_sequential).stream (
IO[str] |None) – where to render; defaults tosys.stderrso the trail never mixes intostdoutdata.
- Raises:
ValueError – if
progress_baris set without a positivetotal, or together withspinner, ifclockis neither"elapsed"nor"eta", or ifliveis not one ofWHEN.
- mark(ok, message, seconds=None)[source]¶
Record one outcome: tally it and render its trail line.
- Parameters:
ok (
bool|None) – whether the operation succeeded (✓) or failed (✘), orNonewhen it was skipped (⊘).seconds (
float|None) – the operation’s own elapsed time. Whentimeris on it is formatted and appended tomessageas(2.3s). Anoperation()handle fills this in from when it was created; pass it yourself when you already hold a duration.
- Return type:
- finish(ok, summary)[source]¶
Render the persistent
{summary}finisher.okpicks its glyph as inmark():Nonecloses a batch that skipped every operation.With an aggregate indicator that drew, it becomes the indicator’s kept line (a spinner’s
ok()/fail()line, or the bar’s replacement line); otherwise, a plain echoed line. The batch’s elapsed time since construction is appended whentimeris on.A batch finishing inside
delaynever draws its indicator, so none of its buffered lines reached the stream. When the trail is the batch’s output (echo_sequentialandvisible), they are echoed plainly along with the finisher, the way a sequential batch prints them: how fast a batch ran must not decide whether its record exists.- Return type:
- operation()[source]¶
Start a timed operation, returning a handle to record its outcome.
The handle captures the current time; call
_Operation.mark()when the work finishes to record its✓/✘outcome with the elapsed time appended (whentimeris on). This is how a batch reports per-operation timings under concurrency, where the trail itself never sees when an operation began:def fetch(feed): op = trail.operation() ok, message = pull(feed) op.mark(ok, message)
- Return type:
_Operation