ProgressBar¶
ProgressBar is the class behind progressbar.progressbar() and every
bar you construct directly. It combines several mixins (stream redirection,
terminal resizing, color/terminal detection) but they are all reachable
through this one class and its constructor.
- class progressbar.bar.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,ProgressBarBaseUpdates 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.
- paused: bool = False
- property dynamic_messages: Any
Deprecated alias for variables, kept for old callers.
- init() None[source]
Reset per-run state so the bar can be started (again).
Called from __init__ and re-run by start(init=True).
- 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
- 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:
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).
- next() Any
Draw 0% on the first call, else update() and return the item.
- increment(value: float = 1, *args: Any, **kwargs: Any) ProgressBar[source]
Advance value by value (default 1), then update().
- 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.
- 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()
- 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.
- property currval: float
Legacy alias for value, kept progressbar-2 compatible.
Constructor arguments worth knowing¶
The table below covers the constructor arguments most scripts actually set.
Argument |
What it does |
|---|---|
|
The value range. Leave |
|
Overrides the default widget list entirely. Leave unset to get
|
|
Plain strings stitched onto the rendered line. |
|
tqdm-style extras: |
|
The stream to draw on. Defaults to |
|
Capture the named stream and print it above the bar instead of letting it interleave with (and corrupt) the redraw. |
|
|
|
Override color and terminal auto-detection explicitly instead of relying on the environment. See Terminal detection for exactly how the automatic values are derived. |
|
Tune how often the bar is allowed ( |
|
When |
|
Pin the rendered width instead of auto-detecting it. See
Terminal detection for how auto-detection
works and what |
|
Justify the rendered line left ( |
|
Seeds the dictionary backing |