-
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathbar.py
More file actions
1801 lines (1554 loc) · 70.6 KB
/
Copy pathbar.py
File metadata and controls
1801 lines (1554 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""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.
"""
from __future__ import annotations
import abc
import collections.abc
import contextlib
import functools
import importlib
import itertools
import logging
import math
import os
import sys
import time
import timeit
import typing
import warnings
import weakref
from copy import deepcopy
from datetime import datetime, timedelta
from types import FrameType, TracebackType
from python_utils import converters
import progressbar.env
import progressbar.terminal
import progressbar.terminal.stream
from . import (
base,
utils,
)
from .terminal import os_specific
try:
# Optional native accelerator, shipped as the ``progressbar2[fast]`` extra
# (the separate ``speedups`` package). When importable, the iterator path
# uses it automatically. Otherwise we fall back to the pure-Python gate.
# Loaded via importlib so type checkers don't try to resolve the optional
# compiled module when it is absent.
_FastBarIterator = importlib.import_module(
'speedups.progressbar',
).FastBarIterator
except Exception: # pragma: no cover - environmental (absent / ABI mismatch)
_FastBarIterator = None
@functools.cache
def _load_widgets() -> typing.Any:
"""Import the widgets module lazily (and once).
The full-bar code needs ``widgets``, but the lean fast path must not pull
it in (it drags the terminal/color tables). Imported via importlib so the
deferred load doesn't read as a static ``bar -> widgets`` import cycle.
Cached with ``functools.cache`` so full-bar render sites don't pay the
``import_module`` lookup on every call.
"""
return importlib.import_module('progressbar.widgets')
logger = logging.getLogger(__name__)
# A `float` hint already accepts `int` under the PEP 484 numeric tower, so
# an explicit `int | float` union would be redundant noise
NumberT = float
ValueT = NumberT | type[base.UnknownLength] | None
T = typing.TypeVar('T')
class ProgressBarMixinBase(abc.ABC):
"""Shared 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`.
"""
_started = False
_finished = False
_last_update_time: float | None = None
#: The terminal width. This should be automatically detected but will
#: fall back to 80 if auto detection is not possible.
term_width: int = 80
#: 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).
widgets: collections.abc.MutableSequence[typing.Any]
#: When going beyond the max_value, raise an error if True or silently
#: ignore otherwise
max_error: bool
#: Prefix the progressbar with the given string
prefix: str | None
#: Suffix the progressbar with the given string
suffix: str | None
#: Justify to the left if `True` or the right if `False`
left_justify: bool
#: The default keyword arguments for the `default_widgets` if no widgets
#: are configured
widget_kwargs: dict[str, typing.Any]
#: 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.
custom_len: collections.abc.Callable[[str], int]
#: The time the progress bar was started
initial_start_time: datetime | None
#: The interval to poll for updates in seconds if there are updates
poll_interval: float | None
#: The minimum interval to poll for updates in seconds even if there are
#: no updates
min_poll_interval: float
#: Deprecated: The number of intervals that can fit on the screen with a
#: minimum of 100
num_intervals: int = 0
#: Deprecated: The `next_update` is kept for compatibility with external
#: libs: https://github.com/WoLpH/python-progressbar/issues/207
next_update: int = 0
#: Current progress (min_value <= value <= max_value)
value: NumberT
#: Previous progress value
previous_value: NumberT | None
#: Value at the last actual redraw (internal, used by the update gate's
#: pixel check, kept separate from the public `previous_value`)
_last_drawn_value: NumberT | None
#: The minimum/start value for the progress bar
min_value: NumberT
#: Maximum (and final) value. Beyond this value an error will be raised
#: unless the `max_error` parameter is `False`.
max_value: ValueT
#: The time the progressbar reached `max_value` or when `finish()` was
#: called.
end_time: datetime | None
#: The time `start()` was called or iteration started.
start_time: datetime | None
#: Seconds between `start_time` and last call to `update()`
seconds_elapsed: float
#: 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.
extra: dict[str, typing.Any]
def get_last_update_time(self) -> datetime | None:
"""Return `last_update_time` as a `datetime`, or `None` if unset."""
if self._last_update_time:
return datetime.fromtimestamp(self._last_update_time)
else:
return None
def set_last_update_time(self, value: datetime | None) -> None:
"""Store `value` as the `last_update_time` epoch timestamp."""
if value:
self._last_update_time = time.mktime(value.timetuple())
else:
self._last_update_time = None
last_update_time = property(get_last_update_time, set_last_update_time)
def __init__(self, **kwargs: typing.Any) -> None: # noqa: B027
"""Do nothing: concrete state is set up by subclasses/mixins."""
def start(self, **kwargs: typing.Any) -> None:
"""Mark the bar as started. Subclasses do the actual rendering."""
self._started = True
def update(self, value: ValueT = None) -> None: # noqa: B027
"""Do nothing: subclasses do the actual rendering."""
def finish(self) -> None: # pragma: no cover
"""Mark the bar as finished. Subclasses do the actual rendering."""
self._finished = True
def __del__(self) -> None:
"""Best-effort `finish()` on teardown if never explicitly finished."""
if not self._finished and self._started: # pragma: no cover
# We're not using contextlib.suppress here because during teardown
# contextlib is not available anymore. Any exception can occur
# here during interpreter shutdown (closed streams, partially
# torn down modules), so we suppress all of them.
try: # noqa: SIM105
self.finish()
except Exception: # noqa: BLE001, S110
pass
def __getstate__(self) -> collections.abc.Mapping[str, typing.Any]:
"""Return the instance `__dict__` for pickling."""
return self.__dict__
def data(self) -> dict[str, typing.Any]: # pragma: no cover
"""Return the widget-facing data dict (see `ProgressBar.data`)."""
raise NotImplementedError()
def started(self) -> bool:
"""Return whether `start()` has (ever) been called."""
return self._finished or self._started
def finished(self) -> bool:
"""Return whether `finish()` has been called."""
return self._finished
class ProgressBarBase(collections.abc.Iterable[NumberT], ProgressBarMixinBase):
"""Adds 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.
"""
_index_counter = itertools.count()
index: int = -1
label: str = ''
def __init__(self, **kwargs: typing.Any) -> None:
"""Assign a process-unique `index` on first construction."""
# Guard against the cooperative chain (or an old-style subclass
# making several explicit parent __init__ calls) reaching this
# method more than once per instance: `index` keeps its class
# default of -1 until the first construction, so each bar
# consumes exactly one counter value.
if self.index == -1:
self.index = next(self._index_counter)
super().__init__(**kwargs)
def __repr__(self) -> str:
"""Return e.g. ``<ProgressBar#3: my label>``."""
label = f': {self.label}' if self.label else ''
return f'<{self.__class__.__name__}#{self.index}{label}>'
class DefaultFdMixin(ProgressBarMixinBase):
"""Formats 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.
"""
# The file descriptor to write to. Defaults to `sys.stderr`
fd: base.TextIO = sys.stderr
#: Set the terminal to be ANSI compatible. If a terminal is ANSI
#: compatible we will automatically enable `colors` and disable
#: `line_breaks`.
is_ansi_terminal: bool | None = False
#: Whether the file descriptor is a terminal or not. This is used to
#: determine whether to use ANSI escape codes or not.
is_terminal: bool | None
#: Whether to print line breaks. This is useful for logging the
#: progressbar. When disabled the current line is overwritten.
line_breaks: bool | None = True
#: 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`.
enable_colors: progressbar.env.ColorSupport = progressbar.env.COLOR_SUPPORT
def __init__(
self,
fd: base.TextIO = sys.stderr,
is_terminal: bool | None = None,
line_breaks: bool | None = None,
enable_colors: progressbar.env.ColorSupport | None = None,
line_offset: int = 0,
**kwargs: typing.Any,
) -> None:
"""Resolve `fd`/ANSI/color state for this bar.
Args:
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__()`.
"""
if fd is sys.stdout:
fd = utils.streams.original_stdout
elif fd is sys.stderr:
fd = utils.streams.original_stderr
fd = self._apply_line_offset(fd, line_offset)
self.fd = fd
self.is_ansi_terminal = progressbar.env.is_ansi_terminal(fd)
self.is_terminal = progressbar.env.is_terminal(fd, is_terminal)
self.line_breaks = self._determine_line_breaks(line_breaks)
self.enable_colors = self._determine_enable_colors(enable_colors)
super().__init__(**kwargs)
def _apply_line_offset(
self,
fd: base.TextIO,
line_offset: int,
) -> base.TextIO:
"""Wrap `fd` in a `LineOffsetStreamWrapper` if `line_offset` is set."""
if line_offset:
return progressbar.terminal.stream.LineOffsetStreamWrapper(
line_offset,
fd,
)
else:
return fd
def _determine_line_breaks(self, line_breaks: bool | None) -> bool | None:
"""Resolve `line_breaks`, autodetecting from `is_terminal` if unset."""
if line_breaks is None:
return progressbar.env.env_flag(
'PROGRESSBAR_LINE_BREAKS',
not self.is_terminal,
)
else:
return line_breaks
def _determine_enable_colors(
self,
enable_colors: progressbar.env.ColorSupport | None,
) -> progressbar.env.ColorSupport:
"""Resolve the effective color support for this bar.
Args:
enable_colors: `None` autodetects from the
`PROGRESSBAR_ENABLE_COLORS`/`FORCE_COLOR` environment
variables and ANSI-terminal detection, in that order.
`True` forces `XTERM_256`, `False` forces `NONE`. Any other
value must already be a `ColorSupport` instance, used as-is.
Returns:
The resolved color support.
Raises:
ValueError: `enable_colors` is not `None`, `True`, `False`, or a
`ColorSupport` instance.
"""
color_support: progressbar.env.ColorSupport
if enable_colors is None:
colors = (
progressbar.env.env_flag('PROGRESSBAR_ENABLE_COLORS'),
progressbar.env.env_flag('FORCE_COLOR'),
self.is_ansi_terminal,
)
for color_enabled in colors:
if color_enabled is not None:
if color_enabled:
color_support = progressbar.env.COLOR_SUPPORT
else:
color_support = progressbar.env.ColorSupport.NONE
break
else:
color_support = progressbar.env.ColorSupport.NONE
elif enable_colors is True:
color_support = progressbar.env.ColorSupport.XTERM_256
elif enable_colors is False:
color_support = progressbar.env.ColorSupport.NONE
elif isinstance(enable_colors, progressbar.env.ColorSupport):
color_support = enable_colors
else:
raise ValueError(f'Invalid color support value: {enable_colors}')
return color_support
def print(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Print to `self.fd` instead of `sys.stdout`."""
print(*args, file=self.fd, **kwargs)
def start(self, **kwargs: typing.Any) -> None:
"""Put the terminal in the console mode the bar needs, then chain."""
os_specific.set_console_mode()
super().start(**kwargs)
def update(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Format the current widgets into one line and write it to `fd`."""
super().update(*args, **kwargs)
line: str = converters.to_unicode(self._format_line())
if not self.enable_colors:
line = utils.no_color(line)
line = line.rstrip() + '\n' if self.line_breaks else '\r' + line
try: # pragma: no cover
self.fd.write(line)
except UnicodeEncodeError: # pragma: no cover
# ``fd`` is a text stream, so write an ASCII-safe *str*: encode
# with 'replace' to drop un-encodable characters, then decode
# back. Writing the raw bytes here would raise ``TypeError``.
self.fd.write(line.encode('ascii', 'replace').decode('ascii'))
def finish(
self,
*args: typing.Any,
**kwargs: typing.Any,
) -> None: # pragma: no cover
"""Restore the console mode and write the final `end` string."""
os_specific.reset_console_mode()
if self._finished:
return
end = kwargs.pop('end', '\n')
super().finish(*args, **kwargs)
if end and not self.line_breaks:
self.fd.write(end)
self.fd.flush()
def _format_line(self) -> str:
"""Join the formatted widgets and justify to `term_width`."""
widgets = ''.join(self._to_unicode(self._format_widgets()))
if self.left_justify:
return widgets.ljust(self.term_width)
else:
return widgets.rjust(self.term_width)
def _format_widgets(self) -> list[str]:
"""Render `self.widgets` to strings, splitting width in two passes.
Pass 1 walks `self.widgets` in order. A widget failing
`check_size` is skipped entirely (no width, no output). A plain
`str` has its length subtracted from the shared `width` budget
immediately. An `AutoWidthWidgetBase` is deferred (its index is
pushed onto `expanding`, so that list ends up in *reverse* index
order) rather than rendered yet. Anything else (a fixed-width
widget) is rendered right away and its length subtracted from
`width`.
Pass 2 divides whatever `width` remains among the deferred
auto-width widgets. `expanding` holds them in reverse index
order and `pop()` takes from the end, so they are processed
front-to-back: the earliest auto-width widget in the bar is
sized first. Each gets `ceil(remaining_width /
remaining_count)`, floored at 0, so an uneven split gives the
larger share to the earlier widgets. Its rendered length is
then subtracted from `width` before the next widget's share is
computed, so a widget rendering shorter or longer than its
allocation shifts the rest.
"""
widgets = _load_widgets()
result = []
expanding = []
width = self.term_width
data = self.data()
for index, widget in enumerate(self.widgets):
if isinstance(
widget,
widgets.WidgetBase,
) and not widget.check_size(self):
continue
elif isinstance(widget, widgets.AutoWidthWidgetBase):
result.append(widget)
expanding.insert(0, index)
elif isinstance(widget, str):
result.append(widget)
width -= self.custom_len(widget) # type: ignore
else:
widget_output = converters.to_unicode(widget(self, data))
result.append(widget_output)
width -= self.custom_len(widget_output) # type: ignore
count = len(expanding)
while expanding:
portion = max(math.ceil(width / count), 0)
index = expanding.pop()
widget = result[index]
count -= 1
widget_output = widget(self, data, portion)
width -= self.custom_len(widget_output) # type: ignore
result[index] = widget_output
return result
@classmethod
def _to_unicode(
cls, args: collections.abc.Iterable[typing.Any]
) -> collections.abc.Iterator[str]:
"""Convert each item in `args` to `str` via `converters.to_unicode`."""
for arg in args:
yield converters.to_unicode(arg)
class _ResizeRegistry:
"""Shared SIGWINCH handling for all resizable progressbars.
A single signal handler dispatches to every live bar. The original
handler is saved when the first bar registers and restored when the
last one unregisters, so overlapping bars can finish in any order
without leaving a dangling handler installed.
"""
bars: typing.ClassVar[weakref.WeakSet[ResizableMixin]] = weakref.WeakSet()
previous_handler: typing.ClassVar[typing.Any] = None
@classmethod
def install(cls, bar: ResizableMixin) -> None:
"""Register `bar` for resize dispatch, installing the handler once.
The process-global `SIGWINCH` handler is only installed (saving
whatever handler was previously set) on the first registration. A
second, third, etc. overlapping bar just joins the `WeakSet`.
"""
import signal
if not hasattr(signal, 'SIGWINCH'): # pragma: no cover
# Not available on Windows
return
if not cls.bars:
cls.previous_handler = signal.getsignal(
signal.SIGWINCH # type: ignore[attr-defined]
)
signal.signal(
signal.SIGWINCH, # type: ignore[attr-defined]
cls.handle_resize,
)
cls.bars.add(bar)
@classmethod
def uninstall(cls, bar: ResizableMixin) -> None:
"""Unregister `bar`, restoring the original handler once empty.
Only the *last* bar to unregister actually restores
`previous_handler` -- other still-live bars (in the `WeakSet`)
keep the shared handler installed regardless of registration
order.
"""
import signal
if not hasattr(signal, 'SIGWINCH'): # pragma: no cover
# Not available on Windows
return
cls.bars.discard(bar)
if not cls.bars:
signal.signal(
signal.SIGWINCH, # type: ignore[attr-defined]
cls.previous_handler,
)
cls.previous_handler = None
@classmethod
def handle_resize(
cls, signum: int | None = None, frame: FrameType | None = None
) -> None:
"""Dispatch a `SIGWINCH` to every currently-registered bar."""
for bar in list(cls.bars):
bar._handle_resize(signum, frame)
class ResizableMixin(ProgressBarMixinBase):
"""Keeps `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.
"""
def __init__(
self, term_width: int | None = None, **kwargs: typing.Any
) -> None:
"""Fix `term_width`, or autodetect it and track further resizes."""
super().__init__(**kwargs)
self.signal_set = False
if term_width:
self.term_width = term_width
else: # pragma: no cover
with contextlib.suppress(Exception):
self._handle_resize()
_ResizeRegistry.install(self)
self.signal_set = True
def _handle_resize(
self, signum: int | None = None, frame: FrameType | None = None
) -> None:
"""Try to catch resize signals sent from the terminal."""
w, _h = utils.get_terminal_size()
self.term_width = w
def finish(self) -> None: # pragma: no cover
"""Unregister from `_ResizeRegistry` if this bar was registered."""
super().finish()
if self.signal_set:
with contextlib.suppress(Exception):
_ResizeRegistry.uninstall(self)
self.signal_set = False
class StdRedirectMixin(DefaultFdMixin):
"""Redirect ``stdout``/``stderr`` so prints appear above the bar.
Args:
redirect_stderr (bool): Capture ``sys.stderr`` and print it above the
bar instead of letting it corrupt the bar.
redirect_stdout (bool): Capture ``sys.stdout`` and 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``.
"""
redirect_stderr: bool = False
redirect_stdout: bool = False
redirect_blank_line: bool = False
stdout: utils.WrappingIO | base.IO[typing.Any]
stderr: utils.WrappingIO | base.IO[typing.Any]
_stdout: base.IO[typing.Any]
_stderr: base.IO[typing.Any]
def __init__(
self,
redirect_stderr: bool = False,
redirect_stdout: bool = False,
redirect_blank_line: bool = False,
**kwargs: typing.Any,
) -> None:
"""Store the redirect flags. Actual wrapping happens in `start()`."""
super().__init__(**kwargs)
self.redirect_stderr = redirect_stderr
self.redirect_stdout = redirect_stdout
# Separate redirected output from the bar with a blank line
self.redirect_blank_line = redirect_blank_line
self._stdout = self.stdout = sys.stdout
self._stderr = self.stderr = sys.stderr
def start(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""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.
"""
if self.redirect_stdout:
utils.streams.wrap_stdout()
if self.redirect_stderr:
utils.streams.wrap_stderr()
self._stdout = utils.streams.original_stdout
self._stderr = utils.streams.original_stderr
self.stdout = utils.streams.stdout
self.stderr = utils.streams.stderr
utils.streams.start_capturing(self)
super().start(*args, **kwargs)
def update(self, value: NumberT | None = None) -> None:
"""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.
"""
cleared = not self.line_breaks and utils.streams.needs_clear()
if cleared:
self.fd.write('\r' + ' ' * self.term_width + '\r')
utils.streams.flush()
if cleared and self.redirect_blank_line:
# Keep a blank line between the redirected output and the bar
self.fd.write('\n')
super().update(value=value)
def finish(self, end: str = '\n') -> None:
"""Finish, then always release the global stream-wrapping state.
The unwrap runs in a `finally` even when the final render raises,
since a leaked listener would corrupt every later progressbar in
the process.
"""
try:
super().finish(end=end)
finally:
utils.streams.stop_capturing(self)
if self.redirect_stdout:
utils.streams.unwrap_stdout()
if self.redirect_stderr:
utils.streams.unwrap_stderr()
class ProgressBar(
StdRedirectMixin,
ResizableMixin,
ProgressBarBase,
):
"""Updates and prints a progress bar for a task of known or unknown length.
Args:
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.
"""
_iterable: collections.abc.Iterator | None
_DEFAULT_MAXVAL: type[base.UnknownLength] = base.UnknownLength
# update every 50 milliseconds (up to a 20 times per second)
_MINIMUM_UPDATE_INTERVAL: float = 0.050
_last_update_time: float | None = None
paused: bool = False
def __init__(
self,
min_value: NumberT = 0,
max_value: ValueT = None,
widgets: collections.abc.Sequence[typing.Any] | None = None,
left_justify: bool = True,
initial_value: NumberT = 0,
poll_interval: timedelta | float | None = None,
widget_kwargs: dict[str, typing.Any] | None = None,
custom_len: collections.abc.Callable[[str], int] = utils.len_color,
max_error: bool = True,
prefix: str | None = None,
suffix: str | None = None,
variables: dict[str, typing.Any] | None = None,
min_poll_interval: timedelta | float | None = None,
desc: str | None = None,
total: ValueT = None,
unit: str = 'it',
unit_scale: bool = False,
postfix: typing.Any = None,
**kwargs: typing.Any,
) -> None:
"""Initializes a progress bar with sane defaults."""
super().__init__(**kwargs)
max_value, poll_interval = self._apply_deprecated_aliases(
max_value, poll_interval, kwargs
)
if max_value is None and total is not None:
# tqdm-style alias for `max_value`
max_value = total
if prefix is None and desc is not None:
# tqdm-style alias for `prefix`
prefix = f'{desc}: '
if max_value and min_value > typing.cast(NumberT, max_value):
raise ValueError(
'Max value needs to be bigger than the min value',
)
self.min_value = min_value
# Legacy issue, `max_value` can be `None` before execution. After
# that it either has a value or is `UnknownLength`
self.max_value = max_value # type: ignore
self.max_error = max_error
self.widgets = self._copy_widgets(widgets)
self.unit = unit
self.unit_scale = unit_scale
# Auto-append a Postfix widget in start() when `postfix` is used
# with the default widgets. Explicit widget lists are left alone.
self._auto_postfix = widgets is None and postfix is not None
self._auto_postfix_added = False
self.prefix = prefix
self.suffix = suffix
self.widget_kwargs = widget_kwargs or {}
self.left_justify = left_justify
self.value = initial_value
self._iterable = None
self.custom_len = custom_len # type: ignore
self.initial_start_time = kwargs.get('start_time')
self.init()
self._setup_poll_intervals(poll_interval, min_poll_interval)
self._seed_variables(variables)
if postfix is not None:
self.variables['postfix'] = postfix
def _apply_deprecated_aliases(
self,
max_value: ValueT,
poll_interval: timedelta | float | None,
kwargs: dict[str, typing.Any],
) -> tuple[ValueT, timedelta | float | None]:
"""Resolve the deprecated ``maxval``/``poll`` keyword aliases.
Emits a :py:class:`DeprecationWarning` for each legacy name that is
used without its modern counterpart and returns the (possibly updated)
``(max_value, poll_interval)`` pair.
"""
if not max_value and kwargs.get('maxval') is not None:
warnings.warn(
'The usage of `maxval` is deprecated, please use '
'`max_value` instead',
DeprecationWarning,
stacklevel=1,
)
max_value = kwargs.get('maxval')
if not poll_interval and kwargs.get('poll'):
warnings.warn(
'The usage of `poll` is deprecated, please use '
'`poll_interval` instead',
DeprecationWarning,
stacklevel=1,
)
poll_interval = kwargs.get('poll')
return max_value, poll_interval
def _copy_widgets(
self, widgets: collections.abc.Sequence[typing.Any] | None
) -> list[typing.Any]:
"""Return a fresh widget list, deep-copying the copy-safe widgets.
Only copy a widget if it's safe to copy. Most widgets are, so that is
assumed to be true unless a widget opts out with ``copy = False``.
"""
result: list[typing.Any] = []
for widget in widgets or []:
if getattr(widget, 'copy', True):
widget = deepcopy(widget)
result.append(widget)
return result
def _setup_poll_intervals(
self,
poll_interval: timedelta | float | None,
min_poll_interval: timedelta | float | None,
) -> None:
"""Convert the poll intervals to seconds and clamp the minimum.
Convert a given timedelta to a floating point number as the internal
interval. We're not using timedelta's internally for two reasons:
1. Backwards compatibility (most important one)
2. Performance. Even though the amount of time it takes to compare a
timedelta with a float versus a float directly is negligible, this
comparison is run for _every_ update. With billions of updates
(downloading a 1GiB file for example) this adds up.
"""
poll_interval = utils.deltas_to_seconds(poll_interval, default=None)
min_poll_interval = utils.deltas_to_seconds(
min_poll_interval,
default=None,
)
self._MINIMUM_UPDATE_INTERVAL = (
utils.deltas_to_seconds(self._MINIMUM_UPDATE_INTERVAL)
or self._MINIMUM_UPDATE_INTERVAL
)
# _MINIMUM_UPDATE_INTERVAL floors low values below.
self.poll_interval = poll_interval
self.min_poll_interval = max(
min_poll_interval or self._MINIMUM_UPDATE_INTERVAL,
self._MINIMUM_UPDATE_INTERVAL,
float(os.environ.get('PROGRESSBAR_MINIMUM_UPDATE_INTERVAL', 0)),
) # type: ignore
def _seed_variables(self, variables: dict[str, typing.Any] | None) -> None:
"""Seed the user-defined variables dict and scan widgets for names.
Builds the ``variables`` mapping read by ``Variable`` and by
``FormatWidgetMixin`` subclasses, and registers a ``None``
placeholder for every ``VariableMixin`` widget whose name isn't
already supplied.
"""
self.variables = utils.AttributeDict(variables or {})
if self.widgets:
widgets_module = _load_widgets()
for widget in self.widgets:
if (
isinstance(widget, widgets_module.VariableMixin)
and widget.name not in self.variables
):
self.variables[widget.name] = None
@property
def dynamic_messages(self) -> typing.Any: # pragma: no cover
"""Deprecated alias for `variables`, kept for old callers."""
return self.variables
@dynamic_messages.setter
def dynamic_messages(self, value: typing.Any) -> None: # pragma: no cover
self.variables = value
def init(self) -> None:
"""Reset per-run state so the bar can be started (again).