progressbar2 4.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/_theme/LICENSE +46 -0
- docs/_theme/flask_theme_support.py +89 -0
- docs/_theme/wolph/layout.html +27 -0
- docs/_theme/wolph/relations.html +19 -0
- docs/_theme/wolph/static/flasky.css_t +431 -0
- docs/_theme/wolph/static/small_flask.css +70 -0
- docs/_theme/wolph/theme.conf +7 -0
- progressbar/__about__.py +27 -0
- progressbar/__init__.py +81 -0
- progressbar/bar.py +1099 -0
- progressbar/base.py +31 -0
- progressbar/env.py +159 -0
- progressbar/multi.py +372 -0
- progressbar/py.typed +0 -0
- progressbar/shortcuts.py +22 -0
- progressbar/terminal/__init__.py +4 -0
- progressbar/terminal/base.py +524 -0
- progressbar/terminal/colors.py +1070 -0
- progressbar/terminal/os_specific/__init__.py +22 -0
- progressbar/terminal/os_specific/posix.py +15 -0
- progressbar/terminal/os_specific/windows.py +137 -0
- progressbar/terminal/stream.py +138 -0
- progressbar/utils.py +445 -0
- progressbar/widgets.py +1564 -0
- progressbar2-4.3.0.dist-info/LICENSE +28 -0
- progressbar2-4.3.0.dist-info/METADATA +442 -0
- progressbar2-4.3.0.dist-info/RECORD +30 -0
- progressbar2-4.3.0.dist-info/WHEEL +5 -0
- progressbar2-4.3.0.dist-info/entry_points.txt +2 -0
- progressbar2-4.3.0.dist-info/top_level.txt +2 -0
progressbar/bar.py
ADDED
|
@@ -0,0 +1,1099 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
import contextlib
|
|
5
|
+
import itertools
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
import timeit
|
|
12
|
+
import warnings
|
|
13
|
+
from copy import deepcopy
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
|
|
16
|
+
from python_utils import converters, types
|
|
17
|
+
|
|
18
|
+
import progressbar.env
|
|
19
|
+
import progressbar.terminal
|
|
20
|
+
import progressbar.terminal.stream
|
|
21
|
+
|
|
22
|
+
from . import (
|
|
23
|
+
base,
|
|
24
|
+
utils,
|
|
25
|
+
widgets,
|
|
26
|
+
widgets as widgets_module, # Avoid name collision
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
# float also accepts integers and longs but we don't want an explicit union
|
|
32
|
+
# due to type checking complexity
|
|
33
|
+
NumberT = float
|
|
34
|
+
|
|
35
|
+
T = types.TypeVar('T')
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ProgressBarMixinBase(abc.ABC):
|
|
39
|
+
_started = False
|
|
40
|
+
_finished = False
|
|
41
|
+
_last_update_time: types.Optional[float] = None
|
|
42
|
+
|
|
43
|
+
#: The terminal width. This should be automatically detected but will
|
|
44
|
+
#: fall back to 80 if auto detection is not possible.
|
|
45
|
+
term_width: int = 80
|
|
46
|
+
#: The widgets to render, defaults to the result of `default_widget()`
|
|
47
|
+
widgets: types.MutableSequence[widgets_module.WidgetBase | str]
|
|
48
|
+
#: When going beyond the max_value, raise an error if True or silently
|
|
49
|
+
#: ignore otherwise
|
|
50
|
+
max_error: bool
|
|
51
|
+
#: Prefix the progressbar with the given string
|
|
52
|
+
prefix: types.Optional[str]
|
|
53
|
+
#: Suffix the progressbar with the given string
|
|
54
|
+
suffix: types.Optional[str]
|
|
55
|
+
#: Justify to the left if `True` or the right if `False`
|
|
56
|
+
left_justify: bool
|
|
57
|
+
#: The default keyword arguments for the `default_widgets` if no widgets
|
|
58
|
+
#: are configured
|
|
59
|
+
widget_kwargs: types.Dict[str, types.Any]
|
|
60
|
+
#: Custom length function for multibyte characters such as CJK
|
|
61
|
+
# mypy and pyright can't agree on what the correct one is... so we'll
|
|
62
|
+
# need to use a helper function :(
|
|
63
|
+
# custom_len: types.Callable[['ProgressBarMixinBase', str], int]
|
|
64
|
+
custom_len: types.Callable[[str], int]
|
|
65
|
+
#: The time the progress bar was started
|
|
66
|
+
initial_start_time: types.Optional[datetime]
|
|
67
|
+
#: The interval to poll for updates in seconds if there are updates
|
|
68
|
+
poll_interval: types.Optional[float]
|
|
69
|
+
#: The minimum interval to poll for updates in seconds even if there are
|
|
70
|
+
#: no updates
|
|
71
|
+
min_poll_interval: float
|
|
72
|
+
|
|
73
|
+
#: Deprecated: The number of intervals that can fit on the screen with a
|
|
74
|
+
#: minimum of 100
|
|
75
|
+
num_intervals: int = 0
|
|
76
|
+
#: Deprecated: The `next_update` is kept for compatibility with external
|
|
77
|
+
#: libs: https://github.com/WoLpH/python-progressbar/issues/207
|
|
78
|
+
next_update: int = 0
|
|
79
|
+
|
|
80
|
+
#: Current progress (min_value <= value <= max_value)
|
|
81
|
+
value: NumberT
|
|
82
|
+
#: Previous progress value
|
|
83
|
+
previous_value: types.Optional[NumberT]
|
|
84
|
+
#: The minimum/start value for the progress bar
|
|
85
|
+
min_value: NumberT
|
|
86
|
+
#: Maximum (and final) value. Beyond this value an error will be raised
|
|
87
|
+
#: unless the `max_error` parameter is `False`.
|
|
88
|
+
max_value: NumberT | types.Type[base.UnknownLength]
|
|
89
|
+
#: The time the progressbar reached `max_value` or when `finish()` was
|
|
90
|
+
#: called.
|
|
91
|
+
end_time: types.Optional[datetime]
|
|
92
|
+
#: The time `start()` was called or iteration started.
|
|
93
|
+
start_time: types.Optional[datetime]
|
|
94
|
+
#: Seconds between `start_time` and last call to `update()`
|
|
95
|
+
seconds_elapsed: float
|
|
96
|
+
|
|
97
|
+
#: Extra data for widgets with persistent state. This is used by
|
|
98
|
+
#: sampling widgets for example. Since widgets can be shared between
|
|
99
|
+
#: multiple progressbars we need to store the state with the progressbar.
|
|
100
|
+
extra: types.Dict[str, types.Any]
|
|
101
|
+
|
|
102
|
+
def get_last_update_time(self) -> types.Optional[datetime]:
|
|
103
|
+
if self._last_update_time:
|
|
104
|
+
return datetime.fromtimestamp(self._last_update_time)
|
|
105
|
+
else:
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
def set_last_update_time(self, value: types.Optional[datetime]):
|
|
109
|
+
if value:
|
|
110
|
+
self._last_update_time = time.mktime(value.timetuple())
|
|
111
|
+
else:
|
|
112
|
+
self._last_update_time = None
|
|
113
|
+
|
|
114
|
+
last_update_time = property(get_last_update_time, set_last_update_time)
|
|
115
|
+
|
|
116
|
+
def __init__(self, **kwargs): # noqa: B027
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
def start(self, **kwargs):
|
|
120
|
+
self._started = True
|
|
121
|
+
|
|
122
|
+
def update(self, value=None): # noqa: B027
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
def finish(self): # pragma: no cover
|
|
126
|
+
self._finished = True
|
|
127
|
+
|
|
128
|
+
def __del__(self):
|
|
129
|
+
if not self._finished and self._started: # pragma: no cover
|
|
130
|
+
self.finish()
|
|
131
|
+
|
|
132
|
+
def __getstate__(self):
|
|
133
|
+
return self.__dict__
|
|
134
|
+
|
|
135
|
+
def data(self) -> types.Dict[str, types.Any]: # pragma: no cover
|
|
136
|
+
raise NotImplementedError()
|
|
137
|
+
|
|
138
|
+
def started(self) -> bool:
|
|
139
|
+
return self._finished or self._started
|
|
140
|
+
|
|
141
|
+
def finished(self) -> bool:
|
|
142
|
+
return self._finished
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class ProgressBarBase(types.Iterable, ProgressBarMixinBase):
|
|
146
|
+
_index_counter = itertools.count()
|
|
147
|
+
index: int = -1
|
|
148
|
+
label: str = ''
|
|
149
|
+
|
|
150
|
+
def __init__(self, **kwargs):
|
|
151
|
+
self.index = next(self._index_counter)
|
|
152
|
+
super().__init__(**kwargs)
|
|
153
|
+
|
|
154
|
+
def __repr__(self):
|
|
155
|
+
label = f': {self.label}' if self.label else ''
|
|
156
|
+
return f'<{self.__class__.__name__}#{self.index}{label}>'
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class DefaultFdMixin(ProgressBarMixinBase):
|
|
160
|
+
# The file descriptor to write to. Defaults to `sys.stderr`
|
|
161
|
+
fd: base.TextIO = sys.stderr
|
|
162
|
+
#: Set the terminal to be ANSI compatible. If a terminal is ANSI
|
|
163
|
+
#: compatible we will automatically enable `colors` and disable
|
|
164
|
+
#: `line_breaks`.
|
|
165
|
+
is_ansi_terminal: bool = False
|
|
166
|
+
#: Whether the file descriptor is a terminal or not. This is used to
|
|
167
|
+
#: determine whether to use ANSI escape codes or not.
|
|
168
|
+
is_terminal: bool
|
|
169
|
+
#: Whether to print line breaks. This is useful for logging the
|
|
170
|
+
#: progressbar. When disabled the current line is overwritten.
|
|
171
|
+
line_breaks: bool = True
|
|
172
|
+
#: Specify the type and number of colors to support. Defaults to auto
|
|
173
|
+
#: detection based on the file descriptor type (i.e. interactive terminal)
|
|
174
|
+
#: environment variables such as `COLORTERM` and `TERM`. Color output can
|
|
175
|
+
#: be forced in non-interactive terminals using the
|
|
176
|
+
#: `PROGRESSBAR_ENABLE_COLORS` environment variable which can also be used
|
|
177
|
+
#: to force a specific number of colors by specifying `24bit`, `256` or
|
|
178
|
+
#: `16`.
|
|
179
|
+
#: For true (24 bit/16M) color support you can use `COLORTERM=truecolor`.
|
|
180
|
+
#: For 256 color support you can use `TERM=xterm-256color`.
|
|
181
|
+
#: For 16 colorsupport you can use `TERM=xterm`.
|
|
182
|
+
enable_colors: progressbar.env.ColorSupport | bool | None = (
|
|
183
|
+
progressbar.env.COLOR_SUPPORT
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def __init__(
|
|
187
|
+
self,
|
|
188
|
+
fd: base.TextIO = sys.stderr,
|
|
189
|
+
is_terminal: bool | None = None,
|
|
190
|
+
line_breaks: bool | None = None,
|
|
191
|
+
enable_colors: progressbar.env.ColorSupport | None = None,
|
|
192
|
+
line_offset: int = 0,
|
|
193
|
+
**kwargs,
|
|
194
|
+
):
|
|
195
|
+
if fd is sys.stdout:
|
|
196
|
+
fd = utils.streams.original_stdout
|
|
197
|
+
elif fd is sys.stderr:
|
|
198
|
+
fd = utils.streams.original_stderr
|
|
199
|
+
|
|
200
|
+
fd = self._apply_line_offset(fd, line_offset)
|
|
201
|
+
self.fd = fd
|
|
202
|
+
self.is_ansi_terminal = progressbar.env.is_ansi_terminal(fd)
|
|
203
|
+
self.is_terminal = self._determine_is_terminal(fd, is_terminal)
|
|
204
|
+
self.line_breaks = self._determine_line_breaks(line_breaks)
|
|
205
|
+
self.enable_colors = self._determine_enable_colors(enable_colors)
|
|
206
|
+
|
|
207
|
+
super().__init__(**kwargs)
|
|
208
|
+
|
|
209
|
+
def _apply_line_offset(
|
|
210
|
+
self,
|
|
211
|
+
fd: base.TextIO,
|
|
212
|
+
line_offset: int,
|
|
213
|
+
) -> base.TextIO:
|
|
214
|
+
if line_offset:
|
|
215
|
+
return progressbar.terminal.stream.LineOffsetStreamWrapper(
|
|
216
|
+
line_offset,
|
|
217
|
+
fd,
|
|
218
|
+
)
|
|
219
|
+
else:
|
|
220
|
+
return fd
|
|
221
|
+
|
|
222
|
+
def _determine_is_terminal(
|
|
223
|
+
self,
|
|
224
|
+
fd: base.TextIO,
|
|
225
|
+
is_terminal: bool | None,
|
|
226
|
+
) -> bool:
|
|
227
|
+
if is_terminal is not None:
|
|
228
|
+
return progressbar.env.is_terminal(fd, is_terminal)
|
|
229
|
+
else:
|
|
230
|
+
return progressbar.env.is_ansi_terminal(fd)
|
|
231
|
+
|
|
232
|
+
def _determine_line_breaks(self, line_breaks: bool | None) -> bool:
|
|
233
|
+
if line_breaks is None:
|
|
234
|
+
return progressbar.env.env_flag(
|
|
235
|
+
'PROGRESSBAR_LINE_BREAKS',
|
|
236
|
+
not self.is_terminal,
|
|
237
|
+
)
|
|
238
|
+
else:
|
|
239
|
+
return bool(line_breaks)
|
|
240
|
+
|
|
241
|
+
def _determine_enable_colors(
|
|
242
|
+
self,
|
|
243
|
+
enable_colors: progressbar.env.ColorSupport | None,
|
|
244
|
+
) -> progressbar.env.ColorSupport:
|
|
245
|
+
if enable_colors is None:
|
|
246
|
+
colors = (
|
|
247
|
+
progressbar.env.env_flag('PROGRESSBAR_ENABLE_COLORS'),
|
|
248
|
+
progressbar.env.env_flag('FORCE_COLOR'),
|
|
249
|
+
self.is_ansi_terminal,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
for color_enabled in colors:
|
|
253
|
+
if color_enabled is not None:
|
|
254
|
+
if color_enabled:
|
|
255
|
+
enable_colors = progressbar.env.COLOR_SUPPORT
|
|
256
|
+
else:
|
|
257
|
+
enable_colors = progressbar.env.ColorSupport.NONE
|
|
258
|
+
break
|
|
259
|
+
else: # pragma: no cover
|
|
260
|
+
# This scenario should never occur because `is_ansi_terminal`
|
|
261
|
+
# should always be `True` or `False`
|
|
262
|
+
raise ValueError('Unable to determine color support')
|
|
263
|
+
|
|
264
|
+
elif enable_colors is True:
|
|
265
|
+
enable_colors = progressbar.env.ColorSupport.XTERM_256
|
|
266
|
+
elif enable_colors is False:
|
|
267
|
+
enable_colors = progressbar.env.ColorSupport.NONE
|
|
268
|
+
elif not isinstance(enable_colors, progressbar.env.ColorSupport):
|
|
269
|
+
raise ValueError(f'Invalid color support value: {enable_colors}')
|
|
270
|
+
|
|
271
|
+
return enable_colors
|
|
272
|
+
|
|
273
|
+
def print(self, *args: types.Any, **kwargs: types.Any) -> None:
|
|
274
|
+
print(*args, file=self.fd, **kwargs)
|
|
275
|
+
|
|
276
|
+
def update(self, *args: types.Any, **kwargs: types.Any) -> None:
|
|
277
|
+
ProgressBarMixinBase.update(self, *args, **kwargs)
|
|
278
|
+
|
|
279
|
+
line: str = converters.to_unicode(self._format_line())
|
|
280
|
+
if not self.enable_colors:
|
|
281
|
+
line = utils.no_color(line)
|
|
282
|
+
|
|
283
|
+
line = line.rstrip() + '\n' if self.line_breaks else '\r' + line
|
|
284
|
+
|
|
285
|
+
try: # pragma: no cover
|
|
286
|
+
self.fd.write(line)
|
|
287
|
+
except UnicodeEncodeError: # pragma: no cover
|
|
288
|
+
self.fd.write(types.cast(str, line.encode('ascii', 'replace')))
|
|
289
|
+
|
|
290
|
+
def finish(
|
|
291
|
+
self,
|
|
292
|
+
*args: types.Any,
|
|
293
|
+
**kwargs: types.Any,
|
|
294
|
+
) -> None: # pragma: no cover
|
|
295
|
+
if self._finished:
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
end = kwargs.pop('end', '\n')
|
|
299
|
+
ProgressBarMixinBase.finish(self, *args, **kwargs)
|
|
300
|
+
|
|
301
|
+
if end and not self.line_breaks:
|
|
302
|
+
self.fd.write(end)
|
|
303
|
+
|
|
304
|
+
self.fd.flush()
|
|
305
|
+
|
|
306
|
+
def _format_line(self):
|
|
307
|
+
'Joins the widgets and justifies the line.'
|
|
308
|
+
widgets = ''.join(self._to_unicode(self._format_widgets()))
|
|
309
|
+
|
|
310
|
+
if self.left_justify:
|
|
311
|
+
return widgets.ljust(self.term_width)
|
|
312
|
+
else:
|
|
313
|
+
return widgets.rjust(self.term_width)
|
|
314
|
+
|
|
315
|
+
def _format_widgets(self):
|
|
316
|
+
result = []
|
|
317
|
+
expanding = []
|
|
318
|
+
width = self.term_width
|
|
319
|
+
data = self.data()
|
|
320
|
+
|
|
321
|
+
for index, widget in enumerate(self.widgets):
|
|
322
|
+
if isinstance(
|
|
323
|
+
widget,
|
|
324
|
+
widgets.WidgetBase,
|
|
325
|
+
) and not widget.check_size(self):
|
|
326
|
+
continue
|
|
327
|
+
elif isinstance(widget, widgets.AutoWidthWidgetBase):
|
|
328
|
+
result.append(widget)
|
|
329
|
+
expanding.insert(0, index)
|
|
330
|
+
elif isinstance(widget, str):
|
|
331
|
+
result.append(widget)
|
|
332
|
+
width -= self.custom_len(widget) # type: ignore
|
|
333
|
+
else:
|
|
334
|
+
widget_output = converters.to_unicode(widget(self, data))
|
|
335
|
+
result.append(widget_output)
|
|
336
|
+
width -= self.custom_len(widget_output) # type: ignore
|
|
337
|
+
|
|
338
|
+
count = len(expanding)
|
|
339
|
+
while expanding:
|
|
340
|
+
portion = max(int(math.ceil(width * 1.0 / count)), 0)
|
|
341
|
+
index = expanding.pop()
|
|
342
|
+
widget = result[index]
|
|
343
|
+
count -= 1
|
|
344
|
+
|
|
345
|
+
widget_output = widget(self, data, portion)
|
|
346
|
+
width -= self.custom_len(widget_output) # type: ignore
|
|
347
|
+
result[index] = widget_output
|
|
348
|
+
|
|
349
|
+
return result
|
|
350
|
+
|
|
351
|
+
@classmethod
|
|
352
|
+
def _to_unicode(cls, args):
|
|
353
|
+
for arg in args:
|
|
354
|
+
yield converters.to_unicode(arg)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
class ResizableMixin(ProgressBarMixinBase):
|
|
358
|
+
def __init__(self, term_width: int | None = None, **kwargs):
|
|
359
|
+
ProgressBarMixinBase.__init__(self, **kwargs)
|
|
360
|
+
|
|
361
|
+
self.signal_set = False
|
|
362
|
+
if term_width:
|
|
363
|
+
self.term_width = term_width
|
|
364
|
+
else: # pragma: no cover
|
|
365
|
+
with contextlib.suppress(Exception):
|
|
366
|
+
self._handle_resize()
|
|
367
|
+
import signal
|
|
368
|
+
|
|
369
|
+
self._prev_handle = signal.getsignal(signal.SIGWINCH)
|
|
370
|
+
signal.signal(signal.SIGWINCH, self._handle_resize)
|
|
371
|
+
self.signal_set = True
|
|
372
|
+
|
|
373
|
+
def _handle_resize(self, signum=None, frame=None):
|
|
374
|
+
'Tries to catch resize signals sent from the terminal.'
|
|
375
|
+
w, h = utils.get_terminal_size()
|
|
376
|
+
self.term_width = w
|
|
377
|
+
|
|
378
|
+
def finish(self): # pragma: no cover
|
|
379
|
+
ProgressBarMixinBase.finish(self)
|
|
380
|
+
if self.signal_set:
|
|
381
|
+
with contextlib.suppress(Exception):
|
|
382
|
+
import signal
|
|
383
|
+
|
|
384
|
+
signal.signal(signal.SIGWINCH, self._prev_handle)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class StdRedirectMixin(DefaultFdMixin):
|
|
388
|
+
redirect_stderr: bool = False
|
|
389
|
+
redirect_stdout: bool = False
|
|
390
|
+
stdout: utils.WrappingIO | base.IO
|
|
391
|
+
stderr: utils.WrappingIO | base.IO
|
|
392
|
+
_stdout: base.IO
|
|
393
|
+
_stderr: base.IO
|
|
394
|
+
|
|
395
|
+
def __init__(
|
|
396
|
+
self,
|
|
397
|
+
redirect_stderr: bool = False,
|
|
398
|
+
redirect_stdout: bool = False,
|
|
399
|
+
**kwargs,
|
|
400
|
+
):
|
|
401
|
+
DefaultFdMixin.__init__(self, **kwargs)
|
|
402
|
+
self.redirect_stderr = redirect_stderr
|
|
403
|
+
self.redirect_stdout = redirect_stdout
|
|
404
|
+
self._stdout = self.stdout = sys.stdout
|
|
405
|
+
self._stderr = self.stderr = sys.stderr
|
|
406
|
+
|
|
407
|
+
def start(self, *args, **kwargs):
|
|
408
|
+
if self.redirect_stdout:
|
|
409
|
+
utils.streams.wrap_stdout()
|
|
410
|
+
|
|
411
|
+
if self.redirect_stderr:
|
|
412
|
+
utils.streams.wrap_stderr()
|
|
413
|
+
|
|
414
|
+
self._stdout = utils.streams.original_stdout
|
|
415
|
+
self._stderr = utils.streams.original_stderr
|
|
416
|
+
|
|
417
|
+
self.stdout = utils.streams.stdout
|
|
418
|
+
self.stderr = utils.streams.stderr
|
|
419
|
+
|
|
420
|
+
utils.streams.start_capturing(self)
|
|
421
|
+
DefaultFdMixin.start(self, *args, **kwargs)
|
|
422
|
+
|
|
423
|
+
def update(self, value: types.Optional[float] = None):
|
|
424
|
+
if not self.line_breaks and utils.streams.needs_clear():
|
|
425
|
+
self.fd.write('\r' + ' ' * self.term_width + '\r')
|
|
426
|
+
|
|
427
|
+
utils.streams.flush()
|
|
428
|
+
DefaultFdMixin.update(self, value=value)
|
|
429
|
+
|
|
430
|
+
def finish(self, end='\n'):
|
|
431
|
+
DefaultFdMixin.finish(self, end=end)
|
|
432
|
+
utils.streams.stop_capturing(self)
|
|
433
|
+
if self.redirect_stdout:
|
|
434
|
+
utils.streams.unwrap_stdout()
|
|
435
|
+
|
|
436
|
+
if self.redirect_stderr:
|
|
437
|
+
utils.streams.unwrap_stderr()
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
class ProgressBar(
|
|
441
|
+
StdRedirectMixin,
|
|
442
|
+
ResizableMixin,
|
|
443
|
+
ProgressBarBase,
|
|
444
|
+
):
|
|
445
|
+
'''The ProgressBar class which updates and prints the bar.
|
|
446
|
+
|
|
447
|
+
Args:
|
|
448
|
+
min_value (int): The minimum/start value for the progress bar
|
|
449
|
+
max_value (int): The maximum/end value for the progress bar.
|
|
450
|
+
Defaults to `_DEFAULT_MAXVAL`
|
|
451
|
+
widgets (list): The widgets to render, defaults to the result of
|
|
452
|
+
`default_widget()`
|
|
453
|
+
left_justify (bool): Justify to the left if `True` or the right if
|
|
454
|
+
`False`
|
|
455
|
+
initial_value (int): The value to start with
|
|
456
|
+
poll_interval (float): The update interval in seconds.
|
|
457
|
+
Note that if your widgets include timers or animations, the actual
|
|
458
|
+
interval may be smaller (faster updates). Also note that updates
|
|
459
|
+
never happens faster than `min_poll_interval` which can be used for
|
|
460
|
+
reduced output in logs
|
|
461
|
+
min_poll_interval (float): The minimum update interval in seconds.
|
|
462
|
+
The bar will _not_ be updated faster than this, despite changes in
|
|
463
|
+
the progress, unless `force=True`. This is limited to be at least
|
|
464
|
+
`_MINIMUM_UPDATE_INTERVAL`. If available, it is also bound by the
|
|
465
|
+
environment variable PROGRESSBAR_MINIMUM_UPDATE_INTERVAL
|
|
466
|
+
widget_kwargs (dict): The default keyword arguments for widgets
|
|
467
|
+
custom_len (function): Method to override how the line width is
|
|
468
|
+
calculated. When using non-latin characters the width
|
|
469
|
+
calculation might be off by default
|
|
470
|
+
max_error (bool): When True the progressbar will raise an error if it
|
|
471
|
+
goes beyond it's set max_value. Otherwise the max_value is simply
|
|
472
|
+
raised when needed
|
|
473
|
+
prefix (str): Prefix the progressbar with the given string
|
|
474
|
+
suffix (str): Prefix the progressbar with the given string
|
|
475
|
+
variables (dict): User-defined variables variables that can be used
|
|
476
|
+
from a label using `format='{variables.my_var}'`. These values can
|
|
477
|
+
be updated using `bar.update(my_var='newValue')` This can also be
|
|
478
|
+
used to set initial values for variables' widgets
|
|
479
|
+
line_offset (int): The number of lines to offset the progressbar from
|
|
480
|
+
your current line. This is useful if you have other output or
|
|
481
|
+
multiple progressbars
|
|
482
|
+
|
|
483
|
+
A common way of using it is like:
|
|
484
|
+
|
|
485
|
+
>>> progress = ProgressBar().start()
|
|
486
|
+
>>> for i in range(100):
|
|
487
|
+
... progress.update(i + 1)
|
|
488
|
+
... # do something
|
|
489
|
+
...
|
|
490
|
+
>>> progress.finish()
|
|
491
|
+
|
|
492
|
+
You can also use a ProgressBar as an iterator:
|
|
493
|
+
|
|
494
|
+
>>> progress = ProgressBar()
|
|
495
|
+
>>> some_iterable = range(100)
|
|
496
|
+
>>> for i in progress(some_iterable):
|
|
497
|
+
... # do something
|
|
498
|
+
... pass
|
|
499
|
+
...
|
|
500
|
+
|
|
501
|
+
Since the progress bar is incredibly customizable you can specify
|
|
502
|
+
different widgets of any type in any order. You can even write your own
|
|
503
|
+
widgets! However, since there are already a good number of widgets you
|
|
504
|
+
should probably play around with them before moving on to create your own
|
|
505
|
+
widgets.
|
|
506
|
+
|
|
507
|
+
The term_width parameter represents the current terminal width. If the
|
|
508
|
+
parameter is set to an integer then the progress bar will use that,
|
|
509
|
+
otherwise it will attempt to determine the terminal width falling back to
|
|
510
|
+
80 columns if the width cannot be determined.
|
|
511
|
+
|
|
512
|
+
When implementing a widget's update method you are passed a reference to
|
|
513
|
+
the current progress bar. As a result, you have access to the
|
|
514
|
+
ProgressBar's methods and attributes. Although there is nothing preventing
|
|
515
|
+
you from changing the ProgressBar you should treat it as read only.
|
|
516
|
+
'''
|
|
517
|
+
|
|
518
|
+
_iterable: types.Optional[types.Iterator]
|
|
519
|
+
|
|
520
|
+
_DEFAULT_MAXVAL: type[base.UnknownLength] = base.UnknownLength
|
|
521
|
+
# update every 50 milliseconds (up to a 20 times per second)
|
|
522
|
+
_MINIMUM_UPDATE_INTERVAL: float = 0.050
|
|
523
|
+
_last_update_time: types.Optional[float] = None
|
|
524
|
+
paused: bool = False
|
|
525
|
+
|
|
526
|
+
def __init__(
|
|
527
|
+
self,
|
|
528
|
+
min_value: NumberT = 0,
|
|
529
|
+
max_value: NumberT | types.Type[base.UnknownLength] | None = None,
|
|
530
|
+
widgets: types.Optional[
|
|
531
|
+
types.Sequence[widgets_module.WidgetBase | str]
|
|
532
|
+
] = None,
|
|
533
|
+
left_justify: bool = True,
|
|
534
|
+
initial_value: NumberT = 0,
|
|
535
|
+
poll_interval: types.Optional[float] = None,
|
|
536
|
+
widget_kwargs: types.Optional[types.Dict[str, types.Any]] = None,
|
|
537
|
+
custom_len: types.Callable[[str], int] = utils.len_color,
|
|
538
|
+
max_error=True,
|
|
539
|
+
prefix=None,
|
|
540
|
+
suffix=None,
|
|
541
|
+
variables=None,
|
|
542
|
+
min_poll_interval=None,
|
|
543
|
+
**kwargs,
|
|
544
|
+
): # sourcery skip: low-code-quality
|
|
545
|
+
'''Initializes a progress bar with sane defaults.'''
|
|
546
|
+
StdRedirectMixin.__init__(self, **kwargs)
|
|
547
|
+
ResizableMixin.__init__(self, **kwargs)
|
|
548
|
+
ProgressBarBase.__init__(self, **kwargs)
|
|
549
|
+
if not max_value and kwargs.get('maxval') is not None:
|
|
550
|
+
warnings.warn(
|
|
551
|
+
'The usage of `maxval` is deprecated, please use '
|
|
552
|
+
'`max_value` instead',
|
|
553
|
+
DeprecationWarning,
|
|
554
|
+
stacklevel=1,
|
|
555
|
+
)
|
|
556
|
+
max_value = kwargs.get('maxval')
|
|
557
|
+
|
|
558
|
+
if not poll_interval and kwargs.get('poll'):
|
|
559
|
+
warnings.warn(
|
|
560
|
+
'The usage of `poll` is deprecated, please use '
|
|
561
|
+
'`poll_interval` instead',
|
|
562
|
+
DeprecationWarning,
|
|
563
|
+
stacklevel=1,
|
|
564
|
+
)
|
|
565
|
+
poll_interval = kwargs.get('poll')
|
|
566
|
+
|
|
567
|
+
if max_value and min_value > types.cast(NumberT, max_value):
|
|
568
|
+
raise ValueError(
|
|
569
|
+
'Max value needs to be bigger than the min value',
|
|
570
|
+
)
|
|
571
|
+
self.min_value = min_value
|
|
572
|
+
# Legacy issue, `max_value` can be `None` before execution. After
|
|
573
|
+
# that it either has a value or is `UnknownLength`
|
|
574
|
+
self.max_value = max_value # type: ignore
|
|
575
|
+
self.max_error = max_error
|
|
576
|
+
|
|
577
|
+
# Only copy the widget if it's safe to copy. Most widgets are so we
|
|
578
|
+
# assume this to be true
|
|
579
|
+
self.widgets = []
|
|
580
|
+
for widget in widgets or []:
|
|
581
|
+
if getattr(widget, 'copy', True):
|
|
582
|
+
widget = deepcopy(widget)
|
|
583
|
+
self.widgets.append(widget)
|
|
584
|
+
|
|
585
|
+
self.prefix = prefix
|
|
586
|
+
self.suffix = suffix
|
|
587
|
+
self.widget_kwargs = widget_kwargs or {}
|
|
588
|
+
self.left_justify = left_justify
|
|
589
|
+
self.value = initial_value
|
|
590
|
+
self._iterable = None
|
|
591
|
+
self.custom_len = custom_len # type: ignore
|
|
592
|
+
self.initial_start_time = kwargs.get('start_time')
|
|
593
|
+
self.init()
|
|
594
|
+
|
|
595
|
+
# Convert a given timedelta to a floating point number as internal
|
|
596
|
+
# interval. We're not using timedelta's internally for two reasons:
|
|
597
|
+
# 1. Backwards compatibility (most important one)
|
|
598
|
+
# 2. Performance. Even though the amount of time it takes to compare a
|
|
599
|
+
# timedelta with a float versus a float directly is negligible, this
|
|
600
|
+
# comparison is run for _every_ update. With billions of updates
|
|
601
|
+
# (downloading a 1GiB file for example) this adds up.
|
|
602
|
+
poll_interval = utils.deltas_to_seconds(poll_interval, default=None)
|
|
603
|
+
min_poll_interval = utils.deltas_to_seconds(
|
|
604
|
+
min_poll_interval,
|
|
605
|
+
default=None,
|
|
606
|
+
)
|
|
607
|
+
self._MINIMUM_UPDATE_INTERVAL = (
|
|
608
|
+
utils.deltas_to_seconds(self._MINIMUM_UPDATE_INTERVAL)
|
|
609
|
+
or self._MINIMUM_UPDATE_INTERVAL
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
# Note that the _MINIMUM_UPDATE_INTERVAL sets the minimum in case of
|
|
613
|
+
# low values.
|
|
614
|
+
self.poll_interval = poll_interval
|
|
615
|
+
self.min_poll_interval = max(
|
|
616
|
+
min_poll_interval or self._MINIMUM_UPDATE_INTERVAL,
|
|
617
|
+
self._MINIMUM_UPDATE_INTERVAL,
|
|
618
|
+
float(os.environ.get('PROGRESSBAR_MINIMUM_UPDATE_INTERVAL', 0)),
|
|
619
|
+
) # type: ignore
|
|
620
|
+
|
|
621
|
+
# A dictionary of names that can be used by Variable and FormatWidget
|
|
622
|
+
self.variables = utils.AttributeDict(variables or {})
|
|
623
|
+
for widget in self.widgets:
|
|
624
|
+
if (
|
|
625
|
+
isinstance(widget, widgets_module.VariableMixin)
|
|
626
|
+
and widget.name not in self.variables
|
|
627
|
+
):
|
|
628
|
+
self.variables[widget.name] = None
|
|
629
|
+
|
|
630
|
+
@property
|
|
631
|
+
def dynamic_messages(self): # pragma: no cover
|
|
632
|
+
return self.variables
|
|
633
|
+
|
|
634
|
+
@dynamic_messages.setter
|
|
635
|
+
def dynamic_messages(self, value): # pragma: no cover
|
|
636
|
+
self.variables = value
|
|
637
|
+
|
|
638
|
+
def init(self):
|
|
639
|
+
'''
|
|
640
|
+
(re)initialize values to original state so the progressbar can be
|
|
641
|
+
used (again).
|
|
642
|
+
'''
|
|
643
|
+
self.previous_value = None
|
|
644
|
+
self.last_update_time = None
|
|
645
|
+
self.start_time = None
|
|
646
|
+
self.updates = 0
|
|
647
|
+
self.end_time = None
|
|
648
|
+
self.extra = dict()
|
|
649
|
+
self._last_update_timer = timeit.default_timer()
|
|
650
|
+
|
|
651
|
+
@property
|
|
652
|
+
def percentage(self) -> float | None:
|
|
653
|
+
'''Return current percentage, returns None if no max_value is given.
|
|
654
|
+
|
|
655
|
+
>>> progress = ProgressBar()
|
|
656
|
+
>>> progress.max_value = 10
|
|
657
|
+
>>> progress.min_value = 0
|
|
658
|
+
>>> progress.value = 0
|
|
659
|
+
>>> progress.percentage
|
|
660
|
+
0.0
|
|
661
|
+
>>>
|
|
662
|
+
>>> progress.value = 1
|
|
663
|
+
>>> progress.percentage
|
|
664
|
+
10.0
|
|
665
|
+
>>> progress.value = 10
|
|
666
|
+
>>> progress.percentage
|
|
667
|
+
100.0
|
|
668
|
+
>>> progress.min_value = -10
|
|
669
|
+
>>> progress.percentage
|
|
670
|
+
100.0
|
|
671
|
+
>>> progress.value = 0
|
|
672
|
+
>>> progress.percentage
|
|
673
|
+
50.0
|
|
674
|
+
>>> progress.value = 5
|
|
675
|
+
>>> progress.percentage
|
|
676
|
+
75.0
|
|
677
|
+
>>> progress.value = -5
|
|
678
|
+
>>> progress.percentage
|
|
679
|
+
25.0
|
|
680
|
+
>>> progress.max_value = None
|
|
681
|
+
>>> progress.percentage
|
|
682
|
+
'''
|
|
683
|
+
if self.max_value is None or self.max_value is base.UnknownLength:
|
|
684
|
+
return None
|
|
685
|
+
elif self.max_value:
|
|
686
|
+
todo = self.value - self.min_value
|
|
687
|
+
total = self.max_value - self.min_value # type: ignore
|
|
688
|
+
percentage = 100.0 * todo / total
|
|
689
|
+
else:
|
|
690
|
+
percentage = 100.0
|
|
691
|
+
|
|
692
|
+
return percentage
|
|
693
|
+
|
|
694
|
+
def data(self) -> types.Dict[str, types.Any]:
|
|
695
|
+
'''
|
|
696
|
+
|
|
697
|
+
Returns:
|
|
698
|
+
dict:
|
|
699
|
+
- `max_value`: The maximum value (can be None with
|
|
700
|
+
iterators)
|
|
701
|
+
- `start_time`: Start time of the widget
|
|
702
|
+
- `last_update_time`: Last update time of the widget
|
|
703
|
+
- `end_time`: End time of the widget
|
|
704
|
+
- `value`: The current value
|
|
705
|
+
- `previous_value`: The previous value
|
|
706
|
+
- `updates`: The total update count
|
|
707
|
+
- `total_seconds_elapsed`: The seconds since the bar started
|
|
708
|
+
- `seconds_elapsed`: The seconds since the bar started modulo
|
|
709
|
+
60
|
|
710
|
+
- `minutes_elapsed`: The minutes since the bar started modulo
|
|
711
|
+
60
|
|
712
|
+
- `hours_elapsed`: The hours since the bar started modulo 24
|
|
713
|
+
- `days_elapsed`: The hours since the bar started
|
|
714
|
+
- `time_elapsed`: The raw elapsed `datetime.timedelta` object
|
|
715
|
+
- `percentage`: Percentage as a float or `None` if no max_value
|
|
716
|
+
is available
|
|
717
|
+
- `dynamic_messages`: Deprecated, use `variables` instead.
|
|
718
|
+
- `variables`: Dictionary of user-defined variables for the
|
|
719
|
+
:py:class:`~progressbar.widgets.Variable`'s.
|
|
720
|
+
|
|
721
|
+
'''
|
|
722
|
+
self._last_update_time = time.time()
|
|
723
|
+
self._last_update_timer = timeit.default_timer()
|
|
724
|
+
elapsed = self.last_update_time - self.start_time # type: ignore
|
|
725
|
+
# For Python 2.7 and higher we have _`timedelta.total_seconds`, but we
|
|
726
|
+
# want to support older versions as well
|
|
727
|
+
total_seconds_elapsed = utils.deltas_to_seconds(elapsed)
|
|
728
|
+
return dict(
|
|
729
|
+
# The maximum value (can be None with iterators)
|
|
730
|
+
max_value=self.max_value,
|
|
731
|
+
# Start time of the widget
|
|
732
|
+
start_time=self.start_time,
|
|
733
|
+
# Last update time of the widget
|
|
734
|
+
last_update_time=self.last_update_time,
|
|
735
|
+
# End time of the widget
|
|
736
|
+
end_time=self.end_time,
|
|
737
|
+
# The current value
|
|
738
|
+
value=self.value,
|
|
739
|
+
# The previous value
|
|
740
|
+
previous_value=self.previous_value,
|
|
741
|
+
# The total update count
|
|
742
|
+
updates=self.updates,
|
|
743
|
+
# The seconds since the bar started
|
|
744
|
+
total_seconds_elapsed=total_seconds_elapsed,
|
|
745
|
+
# The seconds since the bar started modulo 60
|
|
746
|
+
seconds_elapsed=(elapsed.seconds % 60)
|
|
747
|
+
+ (elapsed.microseconds / 1000000.0),
|
|
748
|
+
# The minutes since the bar started modulo 60
|
|
749
|
+
minutes_elapsed=(elapsed.seconds / 60) % 60,
|
|
750
|
+
# The hours since the bar started modulo 24
|
|
751
|
+
hours_elapsed=(elapsed.seconds / (60 * 60)) % 24,
|
|
752
|
+
# The hours since the bar started
|
|
753
|
+
days_elapsed=(elapsed.seconds / (60 * 60 * 24)),
|
|
754
|
+
# The raw elapsed `datetime.timedelta` object
|
|
755
|
+
time_elapsed=elapsed,
|
|
756
|
+
# Percentage as a float or `None` if no max_value is available
|
|
757
|
+
percentage=self.percentage,
|
|
758
|
+
# Dictionary of user-defined
|
|
759
|
+
# :py:class:`progressbar.widgets.Variable`'s
|
|
760
|
+
variables=self.variables,
|
|
761
|
+
# Deprecated alias for `variables`
|
|
762
|
+
dynamic_messages=self.variables,
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
def default_widgets(self):
|
|
766
|
+
if self.max_value:
|
|
767
|
+
return [
|
|
768
|
+
widgets.Percentage(**self.widget_kwargs),
|
|
769
|
+
' ',
|
|
770
|
+
widgets.SimpleProgress(
|
|
771
|
+
format=f'({widgets.SimpleProgress.DEFAULT_FORMAT})',
|
|
772
|
+
**self.widget_kwargs,
|
|
773
|
+
),
|
|
774
|
+
' ',
|
|
775
|
+
widgets.Bar(**self.widget_kwargs),
|
|
776
|
+
' ',
|
|
777
|
+
widgets.Timer(**self.widget_kwargs),
|
|
778
|
+
' ',
|
|
779
|
+
widgets.AdaptiveETA(**self.widget_kwargs),
|
|
780
|
+
]
|
|
781
|
+
else:
|
|
782
|
+
return [
|
|
783
|
+
widgets.AnimatedMarker(**self.widget_kwargs),
|
|
784
|
+
' ',
|
|
785
|
+
widgets.BouncingBar(**self.widget_kwargs),
|
|
786
|
+
' ',
|
|
787
|
+
widgets.Counter(**self.widget_kwargs),
|
|
788
|
+
' ',
|
|
789
|
+
widgets.Timer(**self.widget_kwargs),
|
|
790
|
+
]
|
|
791
|
+
|
|
792
|
+
def __call__(self, iterable, max_value=None):
|
|
793
|
+
'Use a ProgressBar to iterate through an iterable.'
|
|
794
|
+
if max_value is not None:
|
|
795
|
+
self.max_value = max_value
|
|
796
|
+
elif self.max_value is None:
|
|
797
|
+
try:
|
|
798
|
+
self.max_value = len(iterable)
|
|
799
|
+
except TypeError: # pragma: no cover
|
|
800
|
+
self.max_value = base.UnknownLength
|
|
801
|
+
|
|
802
|
+
self._iterable = iter(iterable)
|
|
803
|
+
return self
|
|
804
|
+
|
|
805
|
+
def __iter__(self):
|
|
806
|
+
return self
|
|
807
|
+
|
|
808
|
+
def __next__(self):
|
|
809
|
+
try:
|
|
810
|
+
if self._iterable is None: # pragma: no cover
|
|
811
|
+
value = self.value
|
|
812
|
+
else:
|
|
813
|
+
value = next(self._iterable)
|
|
814
|
+
|
|
815
|
+
if self.start_time is None:
|
|
816
|
+
self.start()
|
|
817
|
+
else:
|
|
818
|
+
self.update(self.value + 1)
|
|
819
|
+
|
|
820
|
+
except StopIteration:
|
|
821
|
+
self.finish()
|
|
822
|
+
raise
|
|
823
|
+
except GeneratorExit: # pragma: no cover
|
|
824
|
+
self.finish(dirty=True)
|
|
825
|
+
raise
|
|
826
|
+
else:
|
|
827
|
+
return value
|
|
828
|
+
|
|
829
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
830
|
+
self.finish(dirty=bool(exc_type))
|
|
831
|
+
|
|
832
|
+
def __enter__(self):
|
|
833
|
+
return self
|
|
834
|
+
|
|
835
|
+
# Create an alias so that Python 2.x won't complain about not being
|
|
836
|
+
# an iterator.
|
|
837
|
+
next = __next__
|
|
838
|
+
|
|
839
|
+
def __iadd__(self, value):
|
|
840
|
+
'Updates the ProgressBar by adding a new value.'
|
|
841
|
+
return self.increment(value)
|
|
842
|
+
|
|
843
|
+
def increment(self, value=1, *args, **kwargs):
|
|
844
|
+
self.update(self.value + value, *args, **kwargs)
|
|
845
|
+
return self
|
|
846
|
+
|
|
847
|
+
def _needs_update(self):
|
|
848
|
+
'Returns whether the ProgressBar should redraw the line.'
|
|
849
|
+
if self.paused:
|
|
850
|
+
return False
|
|
851
|
+
delta = timeit.default_timer() - self._last_update_timer
|
|
852
|
+
if delta < self.min_poll_interval:
|
|
853
|
+
# Prevent updating too often
|
|
854
|
+
return False
|
|
855
|
+
elif self.poll_interval and delta > self.poll_interval:
|
|
856
|
+
# Needs to redraw timers and animations
|
|
857
|
+
return True
|
|
858
|
+
|
|
859
|
+
# Update if value increment is not large enough to
|
|
860
|
+
# add more bars to progressbar (according to current
|
|
861
|
+
# terminal width)
|
|
862
|
+
with contextlib.suppress(Exception):
|
|
863
|
+
divisor: float = self.max_value / self.term_width # type: ignore
|
|
864
|
+
value_divisor = self.value // divisor # type: ignore
|
|
865
|
+
pvalue_divisor = self.previous_value // divisor # type: ignore
|
|
866
|
+
if value_divisor != pvalue_divisor:
|
|
867
|
+
return True
|
|
868
|
+
# No need to redraw yet
|
|
869
|
+
return False
|
|
870
|
+
|
|
871
|
+
def update(self, value=None, force=False, **kwargs):
|
|
872
|
+
'Updates the ProgressBar to a new value.'
|
|
873
|
+
if self.start_time is None:
|
|
874
|
+
self.start()
|
|
875
|
+
|
|
876
|
+
if (
|
|
877
|
+
value is not None
|
|
878
|
+
and value is not base.UnknownLength
|
|
879
|
+
and isinstance(value, int)
|
|
880
|
+
):
|
|
881
|
+
if self.max_value is base.UnknownLength:
|
|
882
|
+
# Can't compare against unknown lengths so just update
|
|
883
|
+
pass
|
|
884
|
+
elif self.min_value > value: # type: ignore
|
|
885
|
+
raise ValueError(
|
|
886
|
+
f'Value {value} is too small. Should be '
|
|
887
|
+
f'between {self.min_value} and {self.max_value}',
|
|
888
|
+
)
|
|
889
|
+
elif self.max_value < value: # type: ignore
|
|
890
|
+
if self.max_error:
|
|
891
|
+
raise ValueError(
|
|
892
|
+
f'Value {value} is too large. Should be between '
|
|
893
|
+
f'{self.min_value} and {self.max_value}',
|
|
894
|
+
)
|
|
895
|
+
else:
|
|
896
|
+
value = self.max_value
|
|
897
|
+
|
|
898
|
+
self.previous_value = self.value
|
|
899
|
+
self.value = value # type: ignore
|
|
900
|
+
|
|
901
|
+
# Save the updated values for dynamic messages
|
|
902
|
+
variables_changed = self._update_variables(kwargs)
|
|
903
|
+
|
|
904
|
+
if self._needs_update() or variables_changed or force:
|
|
905
|
+
self._update_parents(value)
|
|
906
|
+
|
|
907
|
+
def _update_variables(self, kwargs):
|
|
908
|
+
variables_changed = False
|
|
909
|
+
for key, value_ in kwargs.items():
|
|
910
|
+
if key not in self.variables:
|
|
911
|
+
raise TypeError(
|
|
912
|
+
'update() got an unexpected variable name as argument '
|
|
913
|
+
'{key!r}',
|
|
914
|
+
)
|
|
915
|
+
elif self.variables[key] != value_:
|
|
916
|
+
self.variables[key] = kwargs[key]
|
|
917
|
+
variables_changed = True
|
|
918
|
+
return variables_changed
|
|
919
|
+
|
|
920
|
+
def _update_parents(self, value):
|
|
921
|
+
self.updates += 1
|
|
922
|
+
ResizableMixin.update(self, value=value)
|
|
923
|
+
ProgressBarBase.update(self, value=value)
|
|
924
|
+
StdRedirectMixin.update(self, value=value) # type: ignore
|
|
925
|
+
|
|
926
|
+
# Only flush if something was actually written
|
|
927
|
+
self.fd.flush()
|
|
928
|
+
|
|
929
|
+
def start(self, max_value=None, init=True, *args, **kwargs):
|
|
930
|
+
'''Starts measuring time, and prints the bar at 0%.
|
|
931
|
+
|
|
932
|
+
It returns self so you can use it like this:
|
|
933
|
+
|
|
934
|
+
Args:
|
|
935
|
+
max_value (int): The maximum value of the progressbar
|
|
936
|
+
init (bool): (Re)Initialize the progressbar, this is useful if you
|
|
937
|
+
wish to reuse the same progressbar but can be disabled if
|
|
938
|
+
data needs to be persisted between runs
|
|
939
|
+
|
|
940
|
+
>>> pbar = ProgressBar().start()
|
|
941
|
+
>>> for i in range(100):
|
|
942
|
+
... # do something
|
|
943
|
+
... pbar.update(i+1)
|
|
944
|
+
...
|
|
945
|
+
>>> pbar.finish()
|
|
946
|
+
'''
|
|
947
|
+
if init:
|
|
948
|
+
self.init()
|
|
949
|
+
|
|
950
|
+
# Prevent multiple starts
|
|
951
|
+
if self.start_time is not None: # pragma: no cover
|
|
952
|
+
return self
|
|
953
|
+
|
|
954
|
+
if max_value is not None:
|
|
955
|
+
self.max_value = max_value
|
|
956
|
+
|
|
957
|
+
if self.max_value is None:
|
|
958
|
+
self.max_value = self._DEFAULT_MAXVAL
|
|
959
|
+
|
|
960
|
+
StdRedirectMixin.start(self, max_value=max_value)
|
|
961
|
+
ResizableMixin.start(self, max_value=max_value)
|
|
962
|
+
ProgressBarBase.start(self, max_value=max_value)
|
|
963
|
+
|
|
964
|
+
# Constructing the default widgets is only done when we know max_value
|
|
965
|
+
if not self.widgets:
|
|
966
|
+
self.widgets = self.default_widgets()
|
|
967
|
+
|
|
968
|
+
self._init_prefix()
|
|
969
|
+
self._init_suffix()
|
|
970
|
+
self._calculate_poll_interval()
|
|
971
|
+
self._verify_max_value()
|
|
972
|
+
|
|
973
|
+
now = datetime.now()
|
|
974
|
+
self.start_time = self.initial_start_time or now
|
|
975
|
+
self.last_update_time = now
|
|
976
|
+
self._last_update_timer = timeit.default_timer()
|
|
977
|
+
self.update(self.min_value, force=True)
|
|
978
|
+
|
|
979
|
+
return self
|
|
980
|
+
|
|
981
|
+
def _init_suffix(self):
|
|
982
|
+
if self.suffix:
|
|
983
|
+
self.widgets.append(
|
|
984
|
+
widgets.FormatLabel(self.suffix, new_style=True),
|
|
985
|
+
)
|
|
986
|
+
# Unset the suffix variable after applying so an extra start()
|
|
987
|
+
# won't keep copying it
|
|
988
|
+
self.suffix = None
|
|
989
|
+
|
|
990
|
+
def _init_prefix(self):
|
|
991
|
+
if self.prefix:
|
|
992
|
+
self.widgets.insert(
|
|
993
|
+
0,
|
|
994
|
+
widgets.FormatLabel(self.prefix, new_style=True),
|
|
995
|
+
)
|
|
996
|
+
# Unset the prefix variable after applying so an extra start()
|
|
997
|
+
# won't keep copying it
|
|
998
|
+
self.prefix = None
|
|
999
|
+
|
|
1000
|
+
def _verify_max_value(self):
|
|
1001
|
+
if (
|
|
1002
|
+
self.max_value is not base.UnknownLength
|
|
1003
|
+
and self.max_value is not None
|
|
1004
|
+
and self.max_value < 0 # type: ignore
|
|
1005
|
+
):
|
|
1006
|
+
raise ValueError('max_value out of range, got %r' % self.max_value)
|
|
1007
|
+
|
|
1008
|
+
def _calculate_poll_interval(self) -> None:
|
|
1009
|
+
self.num_intervals = max(100, self.term_width)
|
|
1010
|
+
for widget in self.widgets:
|
|
1011
|
+
interval: int | float | None = utils.deltas_to_seconds(
|
|
1012
|
+
getattr(widget, 'INTERVAL', None),
|
|
1013
|
+
default=None,
|
|
1014
|
+
)
|
|
1015
|
+
if interval is not None:
|
|
1016
|
+
self.poll_interval = min(
|
|
1017
|
+
self.poll_interval or interval,
|
|
1018
|
+
interval,
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
def finish(self, end='\n', dirty=False):
|
|
1022
|
+
'''
|
|
1023
|
+
Puts the ProgressBar bar in the finished state.
|
|
1024
|
+
|
|
1025
|
+
Also flushes and disables output buffering if this was the last
|
|
1026
|
+
progressbar running.
|
|
1027
|
+
|
|
1028
|
+
Args:
|
|
1029
|
+
end (str): The string to end the progressbar with, defaults to a
|
|
1030
|
+
newline
|
|
1031
|
+
dirty (bool): When True the progressbar kept the current state and
|
|
1032
|
+
won't be set to 100 percent
|
|
1033
|
+
'''
|
|
1034
|
+
if not dirty:
|
|
1035
|
+
self.end_time = datetime.now()
|
|
1036
|
+
self.update(self.max_value, force=True)
|
|
1037
|
+
|
|
1038
|
+
StdRedirectMixin.finish(self, end=end)
|
|
1039
|
+
ResizableMixin.finish(self)
|
|
1040
|
+
ProgressBarBase.finish(self)
|
|
1041
|
+
|
|
1042
|
+
@property
|
|
1043
|
+
def currval(self):
|
|
1044
|
+
'''
|
|
1045
|
+
Legacy method to make progressbar-2 compatible with the original
|
|
1046
|
+
progressbar package.
|
|
1047
|
+
'''
|
|
1048
|
+
warnings.warn(
|
|
1049
|
+
'The usage of `currval` is deprecated, please use '
|
|
1050
|
+
'`value` instead',
|
|
1051
|
+
DeprecationWarning,
|
|
1052
|
+
stacklevel=1,
|
|
1053
|
+
)
|
|
1054
|
+
return self.value
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
class DataTransferBar(ProgressBar):
|
|
1058
|
+
'''A progress bar with sensible defaults for downloads etc.
|
|
1059
|
+
|
|
1060
|
+
This assumes that the values its given are numbers of bytes.
|
|
1061
|
+
'''
|
|
1062
|
+
|
|
1063
|
+
def default_widgets(self):
|
|
1064
|
+
if self.max_value:
|
|
1065
|
+
return [
|
|
1066
|
+
widgets.Percentage(),
|
|
1067
|
+
' of ',
|
|
1068
|
+
widgets.DataSize('max_value'),
|
|
1069
|
+
' ',
|
|
1070
|
+
widgets.Bar(),
|
|
1071
|
+
' ',
|
|
1072
|
+
widgets.Timer(),
|
|
1073
|
+
' ',
|
|
1074
|
+
widgets.AdaptiveETA(),
|
|
1075
|
+
]
|
|
1076
|
+
else:
|
|
1077
|
+
return [
|
|
1078
|
+
widgets.AnimatedMarker(),
|
|
1079
|
+
' ',
|
|
1080
|
+
widgets.DataSize(),
|
|
1081
|
+
' ',
|
|
1082
|
+
widgets.Timer(),
|
|
1083
|
+
]
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
class NullBar(ProgressBar):
|
|
1087
|
+
'''
|
|
1088
|
+
Progress bar that does absolutely nothing. Useful for single verbosity
|
|
1089
|
+
flags.
|
|
1090
|
+
'''
|
|
1091
|
+
|
|
1092
|
+
def start(self, *args, **kwargs):
|
|
1093
|
+
return self
|
|
1094
|
+
|
|
1095
|
+
def update(self, *args, **kwargs):
|
|
1096
|
+
return self
|
|
1097
|
+
|
|
1098
|
+
def finish(self, *args, **kwargs):
|
|
1099
|
+
return self
|