progressbar.bar module¶
Core ProgressBar implementation: state, redraw gate, and mixins.
ProgressBar is assembled from a stack of small mixins –
DefaultFdMixin (writes formatted lines to a file descriptor),
ResizableMixin (tracks terminal width via SIGWINCH),
StdRedirectMixin (lets print() coexist with the bar) – plus the
redraw machinery: the integer gate and _needs_update() that decide
whether a given update() call actually produces output.
- class progressbar.bar.ProgressBarMixinBase(**kwargs: Any)[source]¶
Bases:
ABCShared state and cooperative no-op interface for progress-bar mixins.
Declares the attributes every mixin/ProgressBar relies on and gives start/update/finish/__init__ trivial bodies so each mixin in the cooperative-inheritance chain can call super().<method>() unconditionally, ending here without a NotImplementedError.
Do nothing: concrete state is set up by subclasses/mixins.
- term_width: int = 80¶
The terminal width. This should be automatically detected but will fall back to 80 if auto detection is not possible.
- widgets: MutableSequence[Any]¶
The widgets to render, defaults to the result of default_widget() (typed loosely as Any to avoid a static bar->widgets import cycle. The public
progressbar()shortcut keeps the precise WidgetBase typing).
- max_error: bool¶
When going beyond the max_value, raise an error if True or silently ignore otherwise
- widget_kwargs: dict[str, Any]¶
The default keyword arguments for the default_widgets if no widgets are configured
- custom_len: Callable[[str], int]¶
Custom length function for multibyte characters such as CJK. A plain
Callable[[str], int]is used (rather than a bound-method signature) because mypy and pyright disagree on the more precise form.
- min_poll_interval: float¶
The minimum interval to poll for updates in seconds even if there are no updates
- num_intervals: int = 0¶
The number of intervals that can fit on the screen with a minimum of 100
- Type:
Deprecated
- next_update: int = 0¶
The next_update is kept for compatibility with external libs: https://github.com/WoLpH/python-progressbar/issues/207
- Type:
Deprecated
- max_value: float | type[<class 'progressbar.base.UnknownLength'>] | None¶
Maximum (and final) value. Beyond this value an error will be raised unless the max_error parameter is False.
- extra: dict[str, Any]¶
Extra data for widgets with persistent state, used by the sampling widgets for example. Keeping it here rather than on the widget lets the widget stay stateless: the state belongs to the bar, so init() clears it on restart and a shared widget cannot mix two bars’ data.
- get_last_update_time() datetime | None[source]¶
Return last_update_time as a datetime, or None if unset.
- set_last_update_time(value: datetime | None) None[source]¶
Store value as the last_update_time epoch timestamp.
- property last_update_time: datetime | None¶
Return last_update_time as a datetime, or None if unset.
- class progressbar.bar.ProgressBarBase(**kwargs: Any)[source]¶
Bases:
Iterable[float],ProgressBarMixinBaseAdds the Iterable protocol and a process-unique index/label.
index identifies a bar among others (e.g. for MultiBar, which uses it to order/label child bars). label is a human-readable name for the same purpose.
Assign a process-unique index on first construction.
- class progressbar.bar.DefaultFdMixin(fd: TextIO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, is_terminal: bool | None = None, line_breaks: bool | None = None, enable_colors: ColorSupport | None = None, line_offset: int = 0, **kwargs: Any)[source]¶
Bases:
ProgressBarMixinBaseFormats and writes the bar’s rendered line to a file descriptor.
Owns ANSI/terminal/color detection for fd (defaults to sys.stderr) and the widget layout pass (_format_widgets) that turns self.widgets into one printable line.
Resolve fd/ANSI/color state for this bar.
- Parameters:
fd – Where to write the bar. sys.stdout/sys.stderr are swapped for the original, unwrapped streams so a bar writing to one doesn’t redirect through its own StdRedirectMixin capture.
is_terminal – Force terminal detection. None autodetects.
line_breaks – Print each redraw on a new line instead of overwriting via a carriage return. None autodetects from is_terminal (and the PROGRESSBAR_LINE_BREAKS environment variable).
enable_colors – Color support override. None autodetects.
line_offset – Number of lines to offset the bar from the current line, via a LineOffsetStreamWrapper around fd.
**kwargs – Forwarded to super().__init__().
- is_ansi_terminal: bool | None = False¶
Set the terminal to be ANSI compatible. If a terminal is ANSI compatible we will automatically enable colors and disable line_breaks.
- is_terminal: bool | None¶
Whether the file descriptor is a terminal or not. This is used to determine whether to use ANSI escape codes or not.
- line_breaks: bool | None = True¶
Whether to print line breaks. This is useful for logging the progressbar. When disabled the current line is overwritten.
- enable_colors: ColorSupport = 0¶
Specify the type and number of colors to support. Defaults to auto detection based on the file descriptor type (i.e. interactive terminal) environment variables such as COLORTERM and TERM. Color output can be forced in non-interactive terminals using the PROGRESSBAR_ENABLE_COLORS environment variable which can also be used to force a specific number of colors by specifying 24bit, 256 or 16. For true (24 bit/16M) color support you can use COLORTERM=truecolor. For 256 color support you can use TERM=xterm-256color. For 16 colorsupport you can use TERM=xterm.
- class progressbar.bar.ResizableMixin(term_width: int | None = None, **kwargs: Any)[source]¶
Bases:
ProgressBarMixinBaseKeeps term_width current via a shared SIGWINCH handler.
With an explicit term_width, that value is fixed and no signal handler is installed. Otherwise, autodetection and _ResizeRegistry.install are attempted and any failure (e.g. no controlling terminal, no SIGWINCH on this platform) is silently swallowed, leaving term_width at its class default.
Fix term_width, or autodetect it and track further resizes.
- class progressbar.bar.StdRedirectMixin(redirect_stderr: bool = False, redirect_stdout: bool = False, redirect_blank_line: bool = False, **kwargs: Any)[source]¶
Bases:
DefaultFdMixinRedirect
stdout/stderrso prints appear above the bar.- Parameters:
redirect_stderr (bool) – Capture
sys.stderrand print it above the bar instead of letting it corrupt the bar.redirect_stdout (bool) – Capture
sys.stdoutand print it above the bar instead of letting it corrupt the bar.redirect_blank_line (bool) – When redirecting, keep a blank line between the redirected output and the bar. Defaults to
False.
Store the redirect flags. Actual wrapping happens in start().
- stdout: WrappingIO | IO[Any]¶
- stderr: WrappingIO | IO[Any]¶
- start(*args: Any, **kwargs: Any) None[source]¶
Wrap stdout/stderr (if requested) and register as a listener.
utils.streams.wrap_stdout/wrap_stderr refcount the wrap, so nested/concurrent bars share one WrappingIO and only the last to finish restores the real stream.
- update(value: float | None = None) None[source]¶
Let buffered prints land above the bar, then redraw.
If a captured print() happened since the last redraw (needs_clear()), the ordering that makes prints appear as normal scrollback above a still-live bar is: erase this bar’s current line, flush the buffered print text through to the real terminal (it becomes a permanent line where the bar used to be), then redraw the bar fresh on the blank line below it.
- 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.
- 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).
- 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.
- class progressbar.bar.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:
ProgressBarA 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.
- class progressbar.bar.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:
ProgressBarProgress 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.
- start(*args: Any, **kwargs: Any) ProgressBar[source]¶
Do nothing and return self.
- update(*args: Any, **kwargs: Any) ProgressBar[source]¶
Do nothing and return self.
- 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.