forked from wolph/python-progressbar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti.py
More file actions
246 lines (200 loc) · 7.27 KB
/
Copy pathmulti.py
File metadata and controls
246 lines (200 loc) · 7.27 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
from __future__ import annotations
import enum
import io
import itertools
import operator
import sys
import threading
import time
import timeit
import types
import typing
from datetime import timedelta
import python_utils
from . import bar, terminal
from .terminal import stream
SortKeyFunc = typing.Callable[[bar.ProgressBar], typing.Any]
class _Update(typing.Protocol):
def __call__(self, force: bool = True, write: bool = True) -> str: ...
class SortKey(str, enum.Enum):
"""
Sort keys for the MultiBar.
This is a string enum, so you can use any
progressbar attribute or property as a sort key.
Note that the multibar defaults to lazily rendering only the changed
progressbars. This means that sorting by dynamic attributes such as
`value` might result in more rendering which can have a small performance
impact.
"""
CREATED = 'index'
LABEL = 'label'
VALUE = 'value'
PERCENTAGE = 'percentage'
class MultiBar(dict[str, bar.ProgressBar]):
fd: typing.TextIO
_buffer: io.StringIO
#: The format for the label to append/prepend to the progressbar
label_format: str
#: Automatically prepend the label to the progressbars
prepend_label: bool
#: Automatically append the label to the progressbars
append_label: bool
#: If `initial_format` is `None`, the progressbar rendering is used
# which will *start* the progressbar. That means the progressbar will
# have no knowledge of your data and will run as an infinite progressbar.
initial_format: str | None
#: If `finished_format` is `None`, the progressbar rendering is used.
finished_format: str | None
#: The multibar updates at a fixed interval regardless of the progressbar
# updates
update_interval: float
remove_finished: float | None
#: The kwargs passed to the progressbar constructor
progressbar_kwargs: dict[str, typing.Any]
#: The progressbar sorting key function
sort_keyfunc: SortKeyFunc
_previous_output: list[str]
_finished_at: dict[bar.ProgressBar, float]
_labeled: set[bar.ProgressBar]
_print_lock: threading.RLock = threading.RLock()
_thread: threading.Thread | None = None
_thread_finished: threading.Event = threading.Event()
_thread_closed: threading.Event = threading.Event()
def __init__(
self,
bars: typing.Iterable[tuple[str, bar.ProgressBar]] | None = None,
fd: typing.TextIO = sys.stderr,
prepend_label: bool = True,
append_label: bool = False,
label_format: str = '{label:20.20} ',
initial_format: str | None = '{label:20.20} Not yet started',
finished_format: str | None = None,
update_interval: float = 1 / 60.0, # 60fps
show_initial: bool = True,
show_finished: bool = True,
remove_finished: timedelta | float = timedelta(seconds=3600),
sort_key: str | SortKey = SortKey.CREATED,
sort_reverse: bool = True,
sort_keyfunc: SortKeyFunc | None = None,
**progressbar_kwargs: typing.Any,
):
self.fd = fd
self.prepend_label = prepend_label
self.append_label = append_label
self.label_format = label_format
self.initial_format = initial_format
self.finished_format = finished_format
self.update_interval = update_interval
self.show_initial = show_initial
self.show_finished = show_finished
self.remove_finished = python_utils.delta_to_seconds_or_none(
remove_finished,
)
self.progressbar_kwargs = progressbar_kwargs
if sort_keyfunc is None:
sort_keyfunc = operator.attrgetter(sort_key)
self.sort_keyfunc = sort_keyfunc
self.sort_reverse = sort_reverse
self._labeled = set()
self._finished_at = {}
self._previous_output = []
self._buffer = io.StringIO()
super().__init__(bars or {})
def __setitem__(self, key: str, bar: bar.ProgressBar):
"""Add a progressbar to the multibar."""
if bar.label != key or not key: # pragma: no branch
bar.label = key
bar.fd = stream.LastLineStream(self.fd)
bar.paused = True
# Essentially `bar.print = self.print`, but `mypy` doesn't
# like that
bar.print = self.print # type: ignore
# Just in case someone is using a progressbar with a custom
# constructor and forgot to call the super constructor
if bar.index == -1:
bar.index = next(
bar._index_counter # pyright: ignore[reportPrivateUsage]
)
super().__setitem__(key, bar)
def __delitem__(self, key: str) -> None:
"""Remove a progressbar from the multibar."""
bar_: bar.ProgressBar = self.pop(key)
self._finished_at.pop(bar_, None)
self._labeled.discard(bar_)
def __getitem__(self, key: str):
"""Get (and create if needed) a progressbar from the multibar."""
try:
return super().__getitem__(key)
except KeyError:
progress = bar.ProgressBar(**self.progressbar_kwargs)
self[key] = progress
return progress
def _label_bar(self, bar: bar.ProgressBar) -> None:
pass
def render(self, flush: bool = True, force: bool = False) -> None:
"""Render the multibar to the given stream."""
pass
def _render_bar(
self,
bar_: bar.ProgressBar,
now: float,
expired: float | None,
) -> typing.Iterable[str]:
pass
def _render_finished_bar(
self,
bar_: bar.ProgressBar,
now: float,
expired: float | None,
update: _Update,
) -> typing.Iterable[str]:
pass
def print(
self,
*args: typing.Any,
end: str = '\n',
offset: int | None = None,
flush: bool = True,
clear: bool = True,
**kwargs: typing.Any,
):
"""
Print to the progressbar stream without overwriting the progressbars.
Args:
end: The string to append to the end of the output
offset: The number of lines to offset the output by. If None, the
output will be printed above the progressbars
flush: Whether to flush the output to the stream
clear: If True, the line will be cleared before printing.
**kwargs: Additional keyword arguments to pass to print
"""
pass
def flush(self) -> None:
pass
def run(self, join: bool = True) -> None:
"""
Start the multibar render loop and run the progressbars until they
have force _thread_finished.
"""
pass
def start(self) -> None:
pass
def join(self, timeout: float | None = None) -> None:
if self._thread is not None:
self._thread_closed.set()
self._thread.join(timeout=timeout)
self._thread = None
def stop(self, timeout: float | None = None):
pass
def get_sorted_bars(self):
pass
def __enter__(self):
self.start()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: types.TracebackType | None,
) -> bool | None:
self.join()