progressbar package

Subpackages

Submodules

Module contents

progressbar2 public API.

Imports are lazy (PEP 562): import progressbar loads almost nothing; each submodule and exported name is imported on first access. This keeps the import light (in particular the widgets and the terminal/color tables are only loaded when actually used) while preserving the full public API.

class progressbar.AbsoluteETA(format_not_started='Estimated finish time:  ----/--/-- --:--:--', format_finished='Finished at: %(elapsed)s', format='Estimated finish time: %(eta)s', **kwargs)[source]

Bases: ETA

Widget which attempts to estimate the absolute time of arrival.

Create an AbsoluteETA with clock-time-flavoured defaults.

class progressbar.AdaptiveETA(exponential_smoothing=True, exponential_smoothing_factor=0.1, **kwargs)[source]

Bases: ETA, SamplesMixin

WidgetBase which attempts to estimate the time of arrival.

Uses a sampled average of the speed based on the 10 last updates. Very convenient for resuming the progress halfway. For an estimate based on an exponential moving average (EMA) of the speed instead of a windowed sample, use SmoothingETA.

Store exponential-smoothing config.

Parameters:
  • exponential_smoothing – Accepted for backward compatibility; not read by AdaptiveETA.__call__, which always averages over the sampled window (see SamplesMixin). Use SmoothingETA for an actual EMA-based estimate.

  • exponential_smoothing_factor – Same caveat as exponential_smoothing.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

exponential_smoothing: bool
exponential_smoothing_factor: float
class progressbar.AdaptiveTransferSpeed(**kwargs: Any)[source]

Bases: FileTransferSpeed, SamplesMixin

Widget for showing the transfer speed based on the last X samples.

Create an AdaptiveTransferSpeed (see FileTransferSpeed).

class progressbar.AnimatedMarker(markers: str = '|/-\\', default: str | None = None, fill: str = '', marker_wrap: str | tuple[str | None, str | None] | None = None, fill_wrap: str | tuple[str | None, str | None] | None = None, **kwargs: Any)[source]

Bases: TimeSensitiveWidgetBase

An animated marker that defaults to appearing as if it were rotating.

Create an AnimatedMarker.

Parameters:
  • markers – Sequence of single-character frames cycled through on every redraw.

  • default – Frame shown once finished when fill is unset; defaults to markers[0].

  • fill – Marker character/callable used to pad the frame to width (see create_marker). Unset means no filling.

  • marker_wrap – Begin/end strings or template wrapped around the marker frame (see create_wrapper).

  • fill_wrap – Same as marker_wrap, for the fill.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.AsyncPool(concurrency: int | None = None, **defaults: Any)[source]

Bases: object

Shared concurrency limit plus per-call defaults for async verbs.

The async sibling of Pool. There is no executor to manage – tasks run on the caller’s event loop – so this is configuration reuse: a concurrency bound and default keywords applied to every call, overridable per call:

async with progressbar.AsyncPool(8) as pool:
    first = await pool.map(fetch, urls)
    async for item, result in pool.imap_unordered(fetch, more):
        ...

Store the concurrency bound and per-call defaults.

imap(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) AsyncIterator[Any][source]

aimap with this pool’s limit and defaults.

imap_unordered(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) AsyncIterator[tuple[Any, Any]][source]

aimap_unordered with this pool’s limit and defaults.

map(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) Coroutine[Any, Any, list[Any]][source]

amap with this pool’s limit and defaults; awaitable.

class progressbar.Bar(marker='#', left='|', right='|', fill=' ', fill_left=True, marker_wrap=None, **kwargs)[source]

Bases: AutoWidthWidgetBase

A progress bar which stretches to fill the line.

Create the bar with its marker and border characters.

Parameters:
  • marker – Character, or (progress, data, width) -> str callable, used for the filled portion.

  • left – Character, or callable, used as the left border.

  • right – Character, or callable, used as the right border.

  • fill – Character used for the empty part of the bar.

  • fill_left – Fill/grow from the left. If False, from the right.

  • marker_wrap – Begin/end strings or template wrapped around a string marker (see create_wrapper). Ignored for a callable marker.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.BouncingBar(marker='#', left='|', right='|', fill=' ', fill_left=True, marker_wrap=None, **kwargs)[source]

Bases: Bar, TimeSensitiveWidgetBase

A bar which has a marker which bounces from side to side.

Create the bar with its marker and border characters.

Parameters:
  • marker – Character, or (progress, data, width) -> str callable, used for the filled portion.

  • left – Character, or callable, used as the left border.

  • right – Character, or callable, used as the right border.

  • fill – Character used for the empty part of the bar.

  • fill_left – Fill/grow from the left. If False, from the right.

  • marker_wrap – Begin/end strings or template wrapped around a string marker (see create_wrapper). Ignored for a callable marker.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

INTERVAL = datetime.timedelta(microseconds=100000)
class progressbar.Counter(format='%(value)d', **kwargs: Any)[source]

Bases: FormatWidgetMixin, WidgetBase

Displays the current count.

Create a Counter with the given format string.

class progressbar.CurrentTime(format='Current Time: %(current_time)s', microseconds=False, **kwargs)[source]

Bases: FormatWidgetMixin, TimeSensitiveWidgetBase

Widget which displays the current (date)time with seconds resolution.

Create a CurrentTime.

Parameters:
  • format – Template string. Adds current_time/ current_datetime keys on top of the usual data() set.

  • microseconds – Keep microsecond resolution instead of truncating to whole seconds.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

INTERVAL = datetime.timedelta(seconds=1)
current_datetime()[source]

Return datetime.now(), seconds-truncated unless microseconds.

current_time()[source]

Return self.current_datetime()’s time-of-day component.

class progressbar.DataSize(variable='value', format='%(scaled)5.1f %(prefix)s%(unit)s', unit='B', prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), **kwargs)[source]

Bases: FormatWidgetMixin, WidgetBase

Widget for showing an amount of data transferred/processed.

Automatically formats the value (assumed to be a count of bytes) with an appropriate sized unit, based on the IEC binary prefixes (powers of 1024).

Create a DataSize.

Parameters:
  • variable – Key in data holding the byte count to render.

  • format – The template string (see FormatWidgetMixin).

  • unit – Unit label appended after the IEC prefix.

  • prefixes – IEC binary prefixes, smallest (none) to largest.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.DataTransferBar(min_value: float = 0, max_value: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, widgets: ~collections.abc.Sequence[~typing.Any] | None = None, left_justify: bool = True, initial_value: float = 0, poll_interval: ~datetime.timedelta | float | None = None, widget_kwargs: dict[str, ~typing.Any] | None = None, custom_len: ~collections.abc.Callable[[str], int] = <function len_color>, max_error: bool = True, prefix: str | None = None, suffix: str | None = None, variables: dict[str, ~typing.Any] | None = None, min_poll_interval: ~datetime.timedelta | float | None = None, desc: str | None = None, total: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, unit: str = 'it', unit_scale: bool = False, postfix: ~typing.Any = None, **kwargs: ~typing.Any)[source]

Bases: ProgressBar

A progress bar with sensible defaults for downloads etc.

This assumes that the values its given are numbers of bytes.

Initializes a progress bar with sane defaults.

default_widgets() list[Any][source]

Build byte-oriented widgets: DataSize instead of ETA text.

class progressbar.DoubleExponentialMovingAverage(alpha: float = 0.5)[source]

Bases: SmoothingAlgorithm

An EMA of an EMA (DEMA), reducing the lag a single EMA carries.

Reacts to recent changes faster than the plain ExponentialMovingAverage.

Set the smoothing factor.

Parameters:

alpha – Weight given to the newest observation in each of the two nested EMAs (0-1); higher tracks recent values more closely, lower smooths harder.

update(new_value: float, elapsed: timedelta) float[source]

Fold new_value into both nested EMAs.

Parameters:
  • new_value – Latest observed value.

  • elapsed – Ignored, as in ExponentialMovingAverage.update.

Returns:

The DEMA estimate, 2 * ema1 - ema2.

class progressbar.DynamicMessage(name, format='{name}: {formatted_value}', width=6, precision=3, **kwargs)[source]

Bases: Variable

Legacy alias for Variable. Prefer Variable in new code.

Kept as a plain subclass (no DeprecationWarning) until the next major version.

Create a Variable rendering the bar variable name.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • formatstr.format() template. Besides the usual keys it gets name, value, width, precision, and formatted_value (value formatted per width/ precision if numeric, else ‘-’ * width if falsy).

  • width – Minimum field width used to format a numeric value.

  • precision – Decimal precision used to format a numeric value.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.ETA(format_not_started='ETA:  --:--:--', format_finished='Time: %(elapsed)8s', format='ETA:  %(eta)8s', format_zero='ETA:  00:00:00', format_na='ETA:      N/A', **kwargs)[source]

Bases: Timer

WidgetBase which attempts to estimate the time of arrival.

Create an ETA, rewriting a legacy bare %s placeholder.

Parameters:
  • format_not_started – Format used before any progress has been made (value == min_value).

  • format_finished – Format used once the bar has finished.

  • format – Format used once an ETA is available.

  • format_zero – Format used when elapsed time is exactly zero.

  • format_na – Format used when no ETA can be computed (unknown max_value).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Rewrites a legacy bare %s placeholder to the named %(eta)s form (see Timer.__init__ for the same elapsed-time shim).

class progressbar.ExponentialMovingAverage(alpha: float = 0.5)[source]

Bases: SmoothingAlgorithm

Exponentially weighted moving average (EMA) of the observed values.

More responsive to recent changes than a simple moving average, with less lag.

Set the smoothing factor.

Parameters:

alpha – Weight given to the newest observation on each update() (0-1); higher tracks recent values more closely, lower smooths harder.

update(new_value: float, elapsed: timedelta) float[source]

Fold new_value into the running average.

Parameters:
  • new_value – Latest observed value.

  • elapsed – Accepted for SmoothingAlgorithm compatibility but not used by this implementation – the average is weighted by call count, not by wall-clock time.

Returns:

The updated EMA.

class progressbar.FastProgressBar(min_value: float = 0, max_value: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, widgets: ~collections.abc.Sequence[~typing.Any] | None = None, left_justify: bool = True, initial_value: float = 0, poll_interval: ~datetime.timedelta | float | None = None, widget_kwargs: dict[str, ~typing.Any] | None = None, custom_len: ~collections.abc.Callable[[str], int] = <function len_color>, max_error: bool = True, prefix: str | None = None, suffix: str | None = None, variables: dict[str, ~typing.Any] | None = None, min_poll_interval: ~datetime.timedelta | float | None = None, desc: str | None = None, total: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, unit: str = 'it', unit_scale: bool = False, postfix: ~typing.Any = None, **kwargs: ~typing.Any)[source]

Bases: ProgressBar

A lean ProgressBar whose render bypasses the widget system.

Reuses the full ProgressBar lifecycle (the next-update gate, the native iterator, stream redirect, resize, start/update/finish) and overrides only the render with a fixed formatter, so the common case is import- and render-cheap. Output stays close to the default look without the gradient.

Initializes a progress bar with sane defaults.

default_widgets() list[Any][source]

Return no widgets – _format_line renders everything itself.

class progressbar.FileTransferSpeed(format='%(scaled)5.1f %(prefix)s%(unit)-s/s', inverse_format='%(scaled)5.1f s/%(prefix)s%(unit)-s', unit='B', prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), **kwargs)[source]

Bases: FormatWidgetMixin, TimeSensitiveWidgetBase

Widget showing the transfer speed (useful for file transfers).

Create a FileTransferSpeed.

Parameters:
  • format – Template used once a speed can be computed.

  • inverse_format – Template used for slow transfers (see __call__), rendering seconds-per-unit instead of units-per-second.

  • unit – Unit label appended after the IEC prefix.

  • prefixes – IEC binary prefixes, smallest (none) to largest.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.FormatCustomText(format: str, mapping: dict[str, Any] | None = None, **kwargs)[source]

Bases: FormatWidgetMixin, WidgetBase

A widget that formats its own mapping instead of data().

Not driven by the bar’s progress at all: update_mapping lets calling code push arbitrary key/value pairs to render, so this acts as a free-form status line alongside the bar. copy = False because its whole point is shared, externally-updated state, unlike ordinary widgets (see WidgetBase’s copy note).

Create a FormatCustomText.

Parameters:
  • format – The template string. Keys come from self.mapping, not the bar’s data().

  • mapping – Initial mapping. Defaults to a copy of the class- level mapping (empty unless a subclass overrides it).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

copy = False
mapping: dict[str, Any] = {}
update_mapping(**mapping: Any)[source]

Merge mapping into self.mapping for the next render.

class progressbar.FormatLabel(format: str, **kwargs: Any)[source]

Bases: FormatWidgetMixin, WidgetBase

Displays a formatted label.

>>> label = FormatLabel('%(value)s', min_width=5, max_width=10)
>>> class Progress:
...     pass
>>> label = FormatLabel('{value} :: {value:^6}', new_style=True)
>>> str(label(Progress, dict(value='test')))
'test ::  test '

Create a FormatLabel for the given format string.

mapping: ClassVar[dict[str, tuple[str, Any]]] = {'elapsed': ('total_seconds_elapsed', <function format_time>), 'finished': ('end_time', None), 'last_update': ('last_update_time', None), 'max': ('max_value', None), 'seconds': ('seconds_elapsed', None), 'start': ('start_time', None), 'value': ('value', None)}
class progressbar.FormatLabelBar(format, **kwargs: Any)[source]

Bases: FormatLabel, Bar

A bar which has a formatted label in the center.

Create a FormatLabelBar with the given format string.

Parameters:
  • format – The label template (see FormatLabel).

  • **kwargs – Forwarded to Bar.__init__.

class progressbar.GranularBar(markers=' ▏▎▍▌▋▊▉█', left='|', right='|', **kwargs)[source]

Bases: AutoWidthWidgetBase

A progressbar with sub-character granularity via multiple markers.

Examples of markers:
  • Smooth: ` ▏▎▍▌▋▊▉█` (default)

  • Bar: ` ▁▂▃▄▅▆▇█`

  • Snake: ` ▖▌▛█`

  • Fade in: ` ░▒▓█`

  • Dots: ` ⡀⡄⡆⡇⣇⣧⣷⣿`

  • Growing circles: ` .oO`

The markers can be accessed through GranularMarkers. GranularMarkers.dots for example

Create a GranularBar with its marker ramp and borders.

Parameters:
  • markers – String of characters to use as granular progress markers. The first character should represent 0% and the last 100%. Ex: ` .oO`.

  • left – String or callable object to use as a left border.

  • right – String or callable object to use as a right border.

  • **kwargs – Forwarded to AutoWidthWidgetBase.__init__.

class progressbar.JobStatusBar(name: str, left='|', right='|', fill=' ', fill_left=True, success_fg_color=((0, 128, 0), (120, 100, 25), 'Green', 2), success_bg_color=None, success_marker='█', failure_fg_color=((255, 0, 0), (0, 100, 50), 'Red', 9), failure_bg_color=None, failure_marker='X', **kwargs)[source]

Bases: Bar, VariableMixin

Widget which displays the job status as markers on the bar.

The status updates can be given either as a boolean or as a string. If it’s a string, it will be displayed as-is. If it’s a boolean, it will be displayed as a marker (default: ‘█’ for success, ‘X’ for failure) configurable through the success_marker and failure_marker parameters. See __init__ for the full parameter list.

Create a JobStatusBar.

Parameters:
  • namedata[‘variables’] key holding each status update.

  • left – The left border of the bar.

  • right – The right border of the bar.

  • fill – The fill character of the bar.

  • fill_left – Whether to fill the bar from the left or the right.

  • success_fg_color – Foreground color for successful jobs.

  • success_bg_color – Background color for successful jobs.

  • success_marker – Marker character for successful jobs.

  • failure_fg_color – Foreground color for failed jobs.

  • failure_bg_color – Background color for failed jobs.

  • failure_marker – Marker character for failed jobs.

  • **kwargs – Forwarded to Bar.__init__.

failure_bg_color: Color | None = None
failure_fg_color: Color | None = ((255, 0, 0), (0, 100, 50), 'Red', 9)
failure_marker: str = 'X'
get_job_markers(progress: ProgressBarMixinBase) list[str][source]

Return this bar’s colored marker history, creating it if needed.

Per-bar marker history, following SamplesMixin’s progress.extra pattern so the widget itself stays stateless; see SamplesMixin.get_sample_times for why that matters.

job_markers: list[str]

Unused, retained for backwards compatibility only.

Per-run marker state lives in progress.extra instead (see get_job_markers()).

success_bg_color: Color | None = None
success_fg_color: Color | None = ((0, 128, 0), (120, 100, 25), 'Green', 2)
success_marker: str = '█'
class progressbar.LineOffsetStreamWrapper(lines: int = 0, stream: TextIO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)[source]

Bases: TextIOOutputWrapper

Writes land a fixed number of lines above the cursor.

Each write moves the cursor up lines rows, writes there, then moves back down, leaving the cursor where it started. Used by ProgressBar’s line_offset= argument to draw a bar above other terminal output instead of at the current line.

Store the offset and the stream writes are redirected to.

Parameters:
  • lines – Number of lines above the current cursor position to write to.

  • stream – The underlying stream to write to.

DOWN = '\x1b[B'

ANSI “cursor down one line” (CSI B).

UP = '\x1b[F'

ANSI “cursor up one line” (CSI F).

write(data: str) int[source]

Write data self.lines rows above the cursor.

Moves the cursor up, writes data with trailing newlines stripped (so the write itself doesn’t move the cursor), then moves back down to restore the original position.

Parameters:

data – Text to write.

Returns:

The length of data before newline-stripping, so callers can detect short writes.

class progressbar.MultiBar(bars: ~collections.abc.Mapping[str, ~progressbar.bar.ProgressBar] | ~collections.abc.Iterable[tuple[str, ~progressbar.bar.ProgressBar]] | None = None, fd: ~typing.TextIO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, prepend_label: bool = True, append_label: bool = False, label_format: str = '{label:20.20} ', initial_format: str | None = '{label:20.20} Not yet started', finished_format: str | None = None, update_interval: float = 0.016666666666666666, show_initial: bool = True, show_finished: bool = True, remove_finished: ~datetime.timedelta | float = datetime.timedelta(seconds=3600), sort_key: str | ~progressbar.multi.SortKey = SortKey.CREATED, sort_reverse: bool = True, sort_keyfunc: ~collections.abc.Callable[[~progressbar.bar.ProgressBar], ~typing.Any] | None = None, *, join_timeout: ~datetime.timedelta | float | None = None, **progressbar_kwargs: ~typing.Any)[source]

Bases: dict[str, ProgressBar]

Render and manage multiple progressbars from background threads.

Adding a bar (multibar[key] = progress, see __setitem__) hands its rendering over to a single daemon thread started by start/__enter__. That thread redraws every bar in place by diffing each frame against the previous one (render) and moving the cursor between lines, rather than reprinting the whole block every time.

On a clean context-manager exit the multibar waits for its render thread via join(). By default (join_timeout=None) that wait is unbounded, so a bar that never finishes blocks the program forever. Pass join_timeout (seconds, or a datetime.timedelta) to bound that wait: once it elapses any still-unfinished bars are abandoned and the render thread (a daemon) is left running so the program can exit. The default preserves the historical wait-forever behavior.

Note

fd is resolved once, from the parameter default, at the time this module is first imported. Unlike a plain ProgressBar, MultiBar is a bare dict subclass with none of DefaultFdMixin’s construction-time sys.stdout/sys.stderr remapping, so replacing sys.stderr after import does not change where an already- or later-constructed MultiBar writes.

Note

The render thread needs real OS threads. Under Pyodide, Thread.start() raises RuntimeError, so with MultiBar(…): (which calls start from __enter__) fails before anything is rendered. Call .render() directly instead of using .start()/the context manager there.

Parameters:
  • bars – Initial bars to add, keyed the same way multibar[key] = progress would add them one at a time.

  • fd – The stream to render to. See the frozen-default note above.

  • prepend_label – Insert a label widget at the start of each bar’s widgets the first time it’s rendered.

  • append_label – Like prepend_label, but appended at the end.

  • label_format – The str.format template for that label widget, formatted with label as a keyword argument.

  • initial_format – The template used for a bar that hasn’t been started yet, formatted with label. If None, the multibar starts the bar itself and renders it normally instead of using a placeholder line.

  • finished_format – The template used once a bar has finished, formatted with label. If None, the bar’s own finished rendering is used instead.

  • update_interval – Seconds the render thread sleeps between frames.

  • show_initial – Whether a not-yet-started bar is rendered at all.

  • show_finished – Whether a finished bar stays visible instead of being hidden (it is still tracked for remove_finished either way).

  • remove_finished – How long a finished bar stays visible before being dropped from the multibar entirely.

  • sort_key – A ProgressBar attribute or property name used to order rendered bars, unless sort_keyfunc is given.

  • sort_reverse – Whether the sort order from sort_key/ sort_keyfunc is reversed.

  • sort_keyfunc – A custom key function overriding sort_key.

  • join_timeout – See above.

  • **progressbar_kwargs – Passed to ProgressBar() when a missing key is looked up and a bar is auto-created for it (see __getitem__).

Initialize the multibar and add any initial bars.

append_label: bool

Automatically append the label to the progressbars

fd: TextIO
finished_format: str | None

If finished_format is None, the progressbar rendering is used.

flush() None[source]

Write the buffered escape sequences and text to fd.

Runs under _print_lock, like print/render, so the fd write happens under the lock as well and concurrent print()/render() calls cannot interleave their output.

get_sorted_bars() list[ProgressBar][source]

Return the current bars, ordered per sort_keyfunc.

Returns:

The bars sorted by sort_keyfunc, reversed if sort_reverse. The values are copied into a list first so a concurrent __setitem__/__delitem__ from another thread (the multibar is a plain dict, not a thread-safe one) can’t mutate it out from under the sort.

initial_format: str | None
join(timeout: float | None = None) None[source]

Ask the render thread to close, then wait for it to exit.

Sets _thread_closed so run’s loop starts checking whether every bar has finished, then blocks on Thread.join. Unlike stop, this does not force the loop to exit early – if bars never finish, timeout (or forever, if None) is the only bound on the wait.

Parameters:

timeout – Seconds to wait for the thread, passed straight through to threading.Thread.join. None waits forever.

join_timeout: float | None
label_format: str

The format for the label to append/prepend to the progressbar

prepend_label: bool

Automatically prepend the label to the progressbars

print(*args: Any, end: str = '\n', offset: int | None = None, flush: bool = True, clear: bool = True, **kwargs: Any) None[source]

Print above (or redraw one line within) the progressbar block.

Moves the cursor up offset lines and writes args through the builtin print, then restores the cursor – but does so two different ways depending on clear:

  • clear=True (the default: a genuine print() call made while bars are active): clears the target line first, then, because the new line permanently occupies a row and pushes everything below it down, clears to the end of the screen and re-emits the whole previous bar frame underneath, so the bars end up back on the lines below the new output.

  • clear=False (used internally by render to redraw a single bar’s row in place): skips both clears and just moves the cursor to the next line after writing, since the caller already overwrote the existing line itself (by prefixing it with a carriage return) instead of inserting a new one, so nothing below it needs to move.

Parameters:
  • *args – Values to print, passed straight through to the builtin print.

  • end – The string to append to the end of the output.

  • offset – How many lines above the cursor’s current position to move before writing. If None, defaults to the number of lines in the last rendered frame, i.e. print above all currently visible bars.

  • flush – Whether to flush the buffered escape sequences to fd immediately.

  • clear – Whether this is a genuine new line of output rather than an in-place bar redraw (see above).

  • **kwargs – Additional keyword arguments passed to the builtin print.

progressbar_kwargs: dict[str, Any]

The kwargs passed to the progressbar constructor

remove_finished: float | None
render(flush: bool = True, force: bool = False) None[source]

Redraw every bar, only touching lines that actually changed.

Builds one output line per visible bar (_render_bar) and diffs it against _previous_output – the frame built by the previous call: lines whose text is unchanged are left alone, lines that changed are reprinted in place through print(clear=False) at their fixed offset, lines for bars that vanished since the last frame are cleared, and a blank line is appended to the buffer for each bar that’s new since the last frame so it doesn’t overwrite existing output.

Parameters:
  • flush – Whether to flush the buffered escape sequences to fd immediately after building this frame.

  • force – Reprint every line even if its text is unchanged – used for the final render before the render thread stops, so a just-finished bar’s finished-format is guaranteed to reach the screen.

run(join: bool = True) None[source]

Render in a loop until stopped or every bar has finished.

This is the render thread’s target when started via start (which passes join=False). It can also be called directly to block the calling thread instead of backgrounding the loop. Each pass renders once and sleeps update_interval. Then, but only if join is true or _thread_closed has been set (i.e. join/stop was called), every current bar is checked in a for/else: finding an unfinished bar just breaks out and the loop continues, but running the for to completion means every bar is finished, so one last forced render is issued, to make sure the just-finished bars’ finished-format actually reaches the screen, and the method returns. stop bypasses all of this by setting _thread_finished directly, which ends the loop on its next while check regardless of bar state.

Parameters:

join – Whether to return as soon as every current bar has finished, rather than only after _thread_closed is set. start() passes False so the background render thread keeps looping, picking up bars added after it started, until join/stop asks it to close.

sort_keyfunc: Callable[[ProgressBar], Any]

The progressbar sorting key function

start() None[source]

Start the daemon thread that renders this multibar.

The thread runs run(join=False) (see there for the loop’s exit conditions) and is a daemon so it never blocks interpreter exit on its own – __exit__/join/stop are what make a clean shutdown actually wait for it.

Not available under Pyodide, which has no real threads (see the class docstring).

stop(timeout: float | None = None) None[source]

Force the render thread to exit, then wait for it.

Sets _thread_finished, which ends run’s loop on its next while check regardless of whether any bar has finished – unlike a plain join(), unfinished bars don’t block this.

Parameters:

timeout – Seconds to wait for the thread, forwarded to join.

update_interval: float
class progressbar.MultiProgressBar(name, markers=' ▁▂▃▄▅▆▇█', **kwargs)[source]

Bases: MultiRangeBar

A bar summarising many sub-progresses as a per-marker histogram.

data[‘variables’][name] holds one entry per sub-progress, each either a 0..1 fraction or a (value, max) pair. get_values buckets them into len(markers) histogram slots (see its docstring for the bucketing rule).

Create a MultiProgressBar.

Parameters:
  • namedata[‘variables’] key holding the sub-progress list (see the class docstring).

  • markers – Ascending-height marker characters, sparsest (0%) to fullest (100%). Reversed internally to match MultiRangeBar’s marker order.

  • **kwargs – Forwarded to MultiRangeBar.__init__.

get_values(progress: ProgressBarMixinBase, data: Data)[source]

Bucket each sub-progress fraction into the marker histogram.

Each value maps to a position along len(markers) - 1 slots; since that position is usually fractional, it spills across its two neighbouring slots weighted by how close it lands to each (e.g. a value 30% of the way from slot 2 to slot 3 adds 0.7 to slot 2’s count and 0.3 to slot 3’s), so the histogram reflects fractional progress rather than rounding every value to its nearest marker.

class progressbar.MultiRangeBar(name, markers, **kwargs: Any)[source]

Bases: Bar, VariableMixin

A bar with multiple sub-ranges, each represented by a different symbol.

The various ranges are represented on a user-defined variable, formatted as

[['Symbol1', amount1], ['Symbol2', amount2], ...]

Create a MultiRangeBar.

Parameters:
  • namedata[‘variables’] key holding the range amounts (see VariableMixin).

  • markers – One single-character marker (or callable, see string_or_lambda) per range, in the same order as the amounts in data[‘variables’][name].

  • **kwargs – Forwarded to Bar.__init__.

get_values(progress: ProgressBarMixinBase, data: Data)[source]

Return the configured [amount, …] list, or [] if unset.

class progressbar.NullBar(min_value: float = 0, max_value: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, widgets: ~collections.abc.Sequence[~typing.Any] | None = None, left_justify: bool = True, initial_value: float = 0, poll_interval: ~datetime.timedelta | float | None = None, widget_kwargs: dict[str, ~typing.Any] | None = None, custom_len: ~collections.abc.Callable[[str], int] = <function len_color>, max_error: bool = True, prefix: str | None = None, suffix: str | None = None, variables: dict[str, ~typing.Any] | None = None, min_poll_interval: ~datetime.timedelta | float | None = None, desc: str | None = None, total: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, unit: str = 'it', unit_scale: bool = False, postfix: ~typing.Any = None, **kwargs: ~typing.Any)[source]

Bases: ProgressBar

Progress bar that does absolutely nothing.

Useful for single verbosity flags, where the same call sites can unconditionally drive a bar whether or not it should render.

Initializes a progress bar with sane defaults.

finish(*args: Any, **kwargs: Any) ProgressBar[source]

Mark the bar finished without rendering anything.

The _finished flag must still flip: MultiBar waits for every member bar’s finished() before its context manager can exit, and would otherwise wait forever on a NullBar member.

start(*args: Any, **kwargs: Any) ProgressBar[source]

Do nothing and return self.

update(*args: Any, **kwargs: Any) ProgressBar[source]

Do nothing and return self.

class progressbar.ParallelFunction(*args, **kwargs)[source]

Bases: Protocol

A function enriched with the parallel batch verbs.

aimap(*iterables: Any, **kwargs: Any) AsyncIterator[Any][source]

Async lazy ordered results; see the module verb.

aimap_unordered(*iterables: Any, **kwargs: Any) AsyncIterator[tuple[Any, Any]][source]

Async completion-order pairs; see the module verb.

amap(*iterables: Any, **kwargs: Any) Coroutine[Any, Any, list[Any]][source]

Async ordered map; see the module verb.

imap(*iterables: Any, **kwargs: Any) Generator[Any, None, None][source]

Lazy ordered results; see the module verb.

imap_unordered(*iterables: Any, **kwargs: Any) Generator[tuple[Any, Any], None, None][source]

Completion-order pairs; see the module verb.

map(*iterables: Any, **kwargs: Any) list[Any][source]

Parallel ordered map over the iterables; see the module verb.

starmap(iterable: Any, **kwargs: Any) list[Any][source]

Parallel map over pre-tupled arguments; see the module verb.

class progressbar.Percentage(format='%(percentage)3d%%', na='N/A%%', **kwargs: Any)[source]

Bases: FormatWidgetMixin, ColoredMixin, WidgetBase

Displays the current percentage as a number with a percent sign.

Create a Percentage.

Parameters:
  • format – Template used once a percentage is available.

  • na – Template used when it isn’t (data[‘percentage’] is None).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

get_format(progress: ProgressBarMixinBase, data: Data, format=None)[source]

Return self.na, colored, when no percentage is available yet.

class progressbar.PercentageLabelBar(format='%(percentage)2d%%', na='N/A%%', **kwargs: Any)[source]

Bases: Percentage, FormatLabelBar

A bar which displays the current percentage in the center.

Create a PercentageLabelBar.

Parameters:
  • format – The percentage template (see Percentage). Uses %2d rather than Percentage’s default %3d, which adds a padding space that looks off-centre here.

  • na – Template used when no percentage is available.

  • **kwargs – Forwarded to FormatLabelBar.__init__.

class progressbar.Pool(workers: int | None = None, kind: str = 'thread', *, executor: Executor | None = None, **defaults: Any)[source]

Bases: object

A reusable executor plus per-call defaults for the sync verbs.

The flat verbs create and destroy an executor per call; a Pool keeps one alive across calls:

with progressbar.Pool(8) as pool:
    first = pool.map(fetch, urls)
    second = pool.map(fetch, more_urls)

Positional shorthand: Pool(8) is eight threads, Pool(8, 'process') eight processes. Pool(executor=existing) adopts a caller-owned executor (never shut down here). Every other keyword becomes a per-call default that individual calls can override.

The executor is created lazily on first use, so an unused Pool(kind='process') spawns nothing.

Validate eagerly (fail fast); create nothing yet.

property executor: Executor

The underlying executor, created on first access.

imap(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) Generator[Any, None, None][source]

imap on this pool’s executor; see the module imap.

imap_unordered(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) Generator[tuple[Any, Any], None, None][source]

imap_unordered on this pool’s executor; see the module verb.

map(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) list[Any][source]

map on this pool’s executor; see the module map.

run(command: Any, items: Iterable[Any], /, **kwargs: Any) list[Any][source]

run a shell command per item on this pool’s executor.

shutdown(wait: bool = True, *, cancel_futures: bool = False) None[source]

Shut down the owned executor; adopted executors are spared.

starmap(fn: Callable[[...], Any], iterable: Iterable[Any], /, **kwargs: Any) list[Any][source]

starmap on this pool’s executor; see the module starmap.

class progressbar.Postfix(name='postfix', prefix=' ', separator=', ', **kwargs: Any)[source]

Bases: VariableMixin, WidgetBase

Displays a live postfix string or key-value mapping.

Create a Postfix.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • prefix – Prepended to the rendered value. Empty when the value itself is falsy (nothing to show).

  • separator – Joins key=value pairs when the variable holds a dict.

  • **kwargs – Forwarded to WidgetBase.__init__.

class progressbar.ProgressBar(min_value: float = 0, max_value: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, widgets: ~collections.abc.Sequence[~typing.Any] | None = None, left_justify: bool = True, initial_value: float = 0, poll_interval: ~datetime.timedelta | float | None = None, widget_kwargs: dict[str, ~typing.Any] | None = None, custom_len: ~collections.abc.Callable[[str], int] = <function len_color>, max_error: bool = True, prefix: str | None = None, suffix: str | None = None, variables: dict[str, ~typing.Any] | None = None, min_poll_interval: ~datetime.timedelta | float | None = None, desc: str | None = None, total: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, unit: str = 'it', unit_scale: bool = False, postfix: ~typing.Any = None, **kwargs: ~typing.Any)[source]

Bases: StdRedirectMixin, ResizableMixin, ProgressBarBase

Updates and prints a progress bar for a task of known or unknown length.

Parameters:
  • min_value – The minimum/start value for the progress bar.

  • max_value – The maximum/end value for the progress bar. Defaults to _DEFAULT_MAXVAL (UnknownLength) if neither this nor total is given.

  • widgets – The widgets to render, defaults to the result of default_widgets().

  • left_justify – Justify to the left if True or the right if False.

  • initial_value – The value to start with.

  • poll_interval – The maximum time between redraws, forcing one even if value hasn’t changed – useful for widgets that show elapsed time or an animation and should keep visibly moving. None (the default) never forces a redraw on time alone. Redraws from value changes can still happen sooner, but never faster than min_poll_interval.

  • min_poll_interval – The minimum time between redraws – a rate limit. The bar is not redrawn faster than this regardless of how fast value changes, unless force=True. Clamped to at least _MINIMUM_UPDATE_INTERVAL, and can be raised further (never lowered) by the PROGRESSBAR_MINIMUM_UPDATE_INTERVAL environment variable.

  • widget_kwargs – Default keyword arguments passed to each widget built by default_widgets().

  • custom_len – Overrides how a rendered widget’s width is measured. The default also strips ANSI color codes before measuring; override this if you use e.g. wide/CJK characters whose on-screen width doesn’t match len().

  • max_error – Raise a ValueError if value goes beyond max_value. If False, value is clamped to max_value instead.

  • prefix – Prefix the progressbar with the given string.

  • suffix – Suffix the progressbar with the given string.

  • variables – User-defined variables that can be used from a label using format=’{variables.my_var}’. These values can be updated using bar.update(my_var=’newValue’). This can also be used to set initial values for variables’ widgets.

  • line_offset – The number of lines to offset the progressbar from your current line. This is useful if you have other output or multiple progressbars.

  • desc – tqdm-style alias for prefix (rendered as f’{desc}: ‘). Ignored if prefix is also given.

  • total – tqdm-style alias for max_value. Ignored if max_value is also given.

  • unit – The unit label used by unit-aware widgets. Defaults to ‘it’.

  • unit_scale – Whether unit-aware widgets should scale the unit (e.g. show 1.2K instead of 1200).

  • postfix – tqdm-style initial value for the postfix variable. With the default widgets, also appends a Postfix widget automatically.

A common way of using it is like:

>>> progress = ProgressBar().start()
>>> for i in range(100):
...     progress.update(i + 1)
...     # do something
>>> progress.finish()

You can also use a ProgressBar as an iterator:

>>> progress = ProgressBar()
>>> some_iterable = range(100)
>>> for i in progress(some_iterable):
...     # do something
...     pass

Since the progress bar is incredibly customizable you can specify different widgets of any type in any order. You can even write your own widgets! However, since there are already a good number of widgets you should probably play around with them before moving on to create your own widgets.

The term_width parameter represents the current terminal width. If the parameter is set to an integer then the progress bar will use that, otherwise it will attempt to determine the terminal width falling back to 80 columns if the width cannot be determined.

When implementing a widget’s update method you are passed a reference to the current progress bar. As a result, you have access to the ProgressBar’s methods and attributes. Although there is nothing preventing you from changing the ProgressBar you should treat it as read only.

Initializes a progress bar with sane defaults.

property currval: float

Legacy alias for value, kept progressbar-2 compatible.

data() dict[str, Any][source]

Return the snapshot dict passed to every widget’s __call__.

Returns:

  • max_value: The configured maximum. None before start(), UnknownLength when the bar has no known length.

  • start_time: When start() ran.

  • last_update_time: Wall-clock time of the most recent redraw.

  • end_time: Set by finish(), None until then.

  • value: The current value.

  • previous_value: The value before the current update() call.

  • updates: Count of redraws performed so far.

  • total_seconds_elapsed: Seconds since start_time, uninterrupted.

  • seconds_elapsed: total_seconds_elapsed modulo 60.

  • minutes_elapsed: Elapsed minutes modulo 60.

  • hours_elapsed: Elapsed hours modulo 24.

  • days_elapsed: Elapsed time in whole days (not modulo).

  • time_elapsed: The raw elapsed datetime.timedelta.

  • percentage: 0-100, or None when max_value is None/UnknownLength (can exceed 100 if max_error is False and value overshoots).

  • unit: The configured unit label (default ‘it’).

  • unit_scale: Whether widgets should scale the unit (e.g. 1.2K instead of 1200).

  • variables: User-defined variables set via the variables= constructor arg or bar.update(name=value); read by Variable and by FormatWidgetMixin subclasses via str.format() substitution.

  • dynamic_messages: Deprecated alias for variables – the same object, kept for old widgets that read this key.

Return type:

dict

This is a pure snapshot of the current state: it performs no timing side effects. The redraw path stamps the update timestamps via _mark_update before the widgets read them.

default_widgets() list[Any][source]

Build the widgets used when no explicit widgets= is given.

Percentage/ETA-style widgets when max_value is known, otherwise an indeterminate animation (no percentage/ETA is computable without a known length).

property dynamic_messages: Any

Deprecated alias for variables, kept for old callers.

finish(end: str = '\n', dirty: bool = False) None[source]

Put the ProgressBar in the finished state.

Also flushes and disables output buffering if this was the last progressbar running.

Parameters:
  • end – The string to end the progressbar with, defaults to a newline.

  • dirty – When True the progressbar kept the current state and won’t be set to 100 percent.

increment(value: float = 1, *args: Any, **kwargs: Any) ProgressBar[source]

Advance value by value (default 1), then update().

init() None[source]

Reset per-run state so the bar can be started (again).

Called from __init__ and re-run by start(init=True).

next() Any

Draw 0% on the first call, else update() and return the item.

paused: bool = False
property percentage: float | None

Return current percentage, returns None if no max_value is given.

>>> progress = ProgressBar()
>>> progress.max_value = 10
>>> progress.min_value = 0
>>> progress.value = 0
>>> progress.percentage
0.0
>>>
>>> progress.value = 1
>>> progress.percentage
10.0
>>> progress.value = 10
>>> progress.percentage
100.0
>>> progress.min_value = -10
>>> progress.percentage
100.0
>>> progress.value = 0
>>> progress.percentage
50.0
>>> progress.value = 5
>>> progress.percentage
75.0
>>> progress.value = -5
>>> progress.percentage
25.0
>>> progress.max_value = None
>>> progress.percentage
start(max_value: float | None = None, init: bool = True, *args: Any, **kwargs: Any) ProgressBar[source]

Start measuring time, print the bar at 0%, and return self.

Returning self allows chaining, as in the example below.

Parameters:
  • max_value – The maximum value of the progressbar.

  • init – (Re)Initialize the progressbar, this is useful if you wish to reuse the same progressbar but can be disabled if data needs to be persisted between runs.

  • *args – Accepted for signature compatibility with subclasses that override start() and forward via super().start(*args, **kwargs). Not used here.

  • **kwargs – Same as *args – accepted but not used here.

>>> pbar = ProgressBar().start()
>>> for i in range(100):
...     # do something
...     pbar.update(i + 1)
>>> pbar.finish()
update(value: float | type[<class 'progressbar.base.UnknownLength'>] | None = None, force: bool = False, **kwargs: Any) None[source]

Update the bar to value and redraw if the gate allows it.

The redraw is skipped unless force is set, a variables= value changed, or _needs_update() decides enough time/progress has passed (see Rendering and the update gate). Widget variables can be updated by keyword: bar.update(my_var=’value’).

Parameters:
  • value – The new progress value. None leaves it unchanged.

  • force – Redraw regardless of the update gate.

  • **kwargs – Widget variable updates, applied to self.variables.

class progressbar.ReverseBar(marker='#', left='|', right='|', fill=' ', fill_left=False, **kwargs)[source]

Bases: Bar

A bar which has a marker that goes from right to left.

Create a Bar that fills from the right by default.

See Bar.__init__ for parameter meaning. fill_left defaults to False here instead of True.

progressbar.RotatingMarker

alias of AnimatedMarker

class progressbar.SimpleProgress(format='%(value_s)s of %(max_value_s)s', **kwargs: Any)[source]

Bases: FormatWidgetMixin, ColoredMixin, WidgetBase

Returns progress as a count of the total (e.g.: “5 of 47”).

Create a SimpleProgress with the given format string.

DEFAULT_FORMAT = '%(value_s)s of %(max_value_s)s'
max_width_cache: dict[str | tuple[NumberT | type[base.UnknownLength] | None, NumberT | type[base.UnknownLength] | None], int | None]
class progressbar.SmoothingAlgorithm(**kwargs: Any)[source]

Bases: ABC

Contract for a stateful value smoother fed one sample at a time.

Configure the algorithm.

Parameters:

**kwargs – Algorithm-specific parameters (e.g. alpha).

abstractmethod update(new_value: float, elapsed: timedelta) float[source]

Fold new_value in and return the smoothed value.

class progressbar.SmoothingETA(smoothing_algorithm: type[SmoothingAlgorithm] = <class 'progressbar.algorithms.ExponentialMovingAverage'>, smoothing_parameters: dict[str, float] | None=None, **kwargs)[source]

Bases: ETA

WidgetBase which estimates the ETA from an exponential moving average.

EMA applies more weight to recent data points and less to older ones, and doesn’t require storing all past values. This approach works well with varying data points and smooths out fluctuations effectively.

Instantiate the smoothing algorithm.

Parameters:
  • smoothing_algorithmSmoothingAlgorithm subclass to instantiate. Defaults to ExponentialMovingAverage.

  • smoothing_parameters – Keyword arguments passed to smoothing_algorithm’s constructor.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

smoothing_algorithm: SmoothingAlgorithm
smoothing_parameters: dict[str, float]
class progressbar.SortKey(*values)[source]

Bases: str, Enum

Sort keys for the MultiBar.

This is a string enum, so you can use any progressbar attribute or property as a sort key.

The multibar defaults to lazily rendering only the changed progressbars, so sorting by dynamic attributes such as value can trigger extra rendering with a small performance impact.

CREATED = 'index'
LABEL = 'label'
PERCENTAGE = 'percentage'
VALUE = 'value'
class progressbar.Timer(format='Elapsed Time: %(elapsed)s', **kwargs: Any)[source]

Bases: FormatLabel, TimeSensitiveWidgetBase

WidgetBase which displays the elapsed seconds.

Create a Timer, rewriting a legacy bare %s placeholder.

Very old configs used a bare %s placeholder for the elapsed time. It is silently rewritten here to the named %(elapsed)s form this widget actually formats with.

static format_time(timestamp: timedelta | date | datetime | str | int | float | None, precision: timedelta = datetime.timedelta(seconds=1)) str

Formats timedelta/datetime/seconds.

>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> format_time(None)
'--:--:--'
>>> format_time(format_time)
Traceback (most recent call last):
    ...
TypeError: Unknown type ...
class progressbar.UnitProgress(unit=<object object>, unit_scale=<object object>, **kwargs: Any)[source]

Bases: WidgetBase

Displays progress as a count with an optional unit and 1024 scaling.

Create a UnitProgress.

Parameters:
  • unit – Unit label. Defaults to following data[‘unit’] (the bar’s own unit=) rather than a fixed value.

  • unit_scale – Whether to IEC-scale the count. Defaults to following data[‘unit_scale’].

  • **kwargs – Forwarded to WidgetBase.__init__.

unit: str
unit_scale: bool
class progressbar.UnknownLength[source]

Bases: object

The total amount of work is not knowable in advance.

Passed as max_value for an iterable with no __len__ (a generator, a stream) so the bar renders progress without a percentage or an ETA.

class progressbar.Variable(name, format='{name}: {formatted_value}', width=6, precision=3, **kwargs)[source]

Bases: FormatWidgetMixin, VariableMixin, WidgetBase

Displays a custom variable.

Create a Variable rendering the bar variable name.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • formatstr.format() template. Besides the usual keys it gets name, value, width, precision, and formatted_value (value formatted per width/ precision if numeric, else ‘-’ * width if falsy).

  • width – Minimum field width used to format a numeric value.

  • precision – Decimal precision used to format a numeric value.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.VariableMixin(name, **kwargs: Any)[source]

Bases: _WidgetKwargsSink

Mixin to display a custom user variable.

Store the data[‘variables’] key this widget reads.

Parameters:
  • name – A single word, used to look up the value in data[‘variables’]/bar.update(name=value).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Raises:
progressbar.current_task_bar() ProgressBar | None[source]

Return the calling task’s own progress bar, if it has one.

Inside a function executed by progressbar.map/amap with bar='multi' this returns the per-task bar so the worker can report sub-progress (current_task_bar().update(i)). Anywhere else – including process-pool workers, which cannot share a bar object with the parent in v1 – it returns None.

progressbar.len_color(value: str | bytes) int[source]

Return the length of value without ANSI escape codes.

>>> len_color(b'[1234]abc')
3
>>> len_color('[1234]abc')
3
>>> len_color('[1234]abc')
3
progressbar.parallel(**config: Any) Callable[[Callable[[...], Any]], ParallelFunction][source]

Attach the parallel batch verbs to a function.

Parameters:

**config – Default keywords for every attached verb (workers, pool, bar, on_error, …); individual calls override them.

Returns:

A decorator returning the same function object with .map, .imap, .imap_unordered, .starmap, .amap, .aimap and .aimap_unordered attached.

Raises:

TypeError – The target is not a plain named function. Lambdas and bound methods are rejected because pool='process' pickles the function by qualified name.

progressbar.process_map(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) list[Any][source]

map pinned to a process pool (tqdm-compatible spelling).

progressbar.progressbar(iterator: collections.abc.Iterable[T], min_value: bar.NumberT = 0, max_value: bar.ValueT = None, widgets: collections.abc.Sequence[widgets_module.WidgetBase | str] | None = None, prefix: str | None = None, suffix: str | None = None, fast: bool | None = None, desc: str | None = None, total: bar.ValueT = None, unit: str = 'it', unit_scale: bool = False, postfix: Any = None, **kwargs: Any) collections.abc.Iterator[T][source]

Wrap an iterable so iterating it renders a progress bar.

The common case needs nothing but the iterable:

for item in progressbar(items):
    ...
Parameters:
  • iterator – The iterable to wrap. Its length is used as the total when it has one; otherwise pass max_value, or accept a bar with no percentage or ETA.

  • min_value – Value the bar starts from. Only worth changing when progress does not begin at zero.

  • max_value – Value counted as complete. Defaults to the iterable’s length, or UnknownLength when it has none.

  • widgets – Replaces the default bar layout entirely. Passing this forces the full widget machinery. See the widget reference for what can go in it.

  • prefix – Text before the bar. desc is the tqdm-style alias.

  • suffix – Text after the bar.

  • fast – Only False has an effect: it always uses the full widget bar. True is the same as leaving it unset – it cannot force the fast path when another argument below rules it out. Mainly useful for benchmarking.

  • desc – tqdm-compatible alias for prefix.

  • total – tqdm-compatible alias for max_value.

  • unit – Noun for one item, shown in the rate. Anything other than the default forces the full widget bar.

  • unit_scale – Scale counts by IEC binary prefixes, base 1024, so 1200 renders as 1.2 Kiit. Forces the full widget bar.

  • postfix – Values rendered after the bar. Through this entry point they are fixed for the run, since the bar itself is not returned, leaving no handle to refresh them through. Forces the full widget bar.

  • **kwargs – Passed through to the underlying bar. Supplying variables forces the full widget bar.

Returns:

An iterator yielding the same items, advancing the bar as it goes.

progressbar.starmap(fn: Callable[[...], Any], iterable: Iterable[Any], /, **kwargs: Any) list[Any][source]

map over pre-tupled arguments (multiprocessing.Pool.starmap).

starmap(fn, [(1, 2), (3, 4)]) calls fn(1, 2) and fn(3, 4) in parallel. See execute for keywords.

progressbar.thread_map(fn: Callable[[...], Any], /, *iterables: Iterable[Any], **kwargs: Any) list[Any][source]

map pinned to a thread pool (tqdm-compatible spelling).