0
# Progress Tracking
1
2
Core progress bar functionality providing context managers, iterator adapters, and comprehensive progress monitoring capabilities. Supports multiple modes of operation including automatic counting, manual percentage control, and unknown total scenarios.
3
4
## Capabilities
5
6
### Alive Bar Context Manager
7
8
The primary interface for creating progress bars. Returns a context manager that yields a bar handle for controlling progress updates, text messages, and monitoring.
9
10
```python { .api }
11
def alive_bar(total: Optional[int] = None, *, calibrate: Optional[int] = None, **options: Any):
12
"""
13
Create an alive progress bar context manager.
14
15
Parameters:
16
- total (Optional[int]): Expected total count. If None, creates unknown mode bar
17
- calibrate (Optional[int]): Maximum theoretical throughput for animation calibration
18
- **options: Configuration options (see Configuration documentation)
19
20
Returns:
21
Context manager yielding AliveBarHandle object
22
23
Raises:
24
- TypeError: If total is not an integer
25
- ValueError: If configuration options are invalid
26
"""
27
```
28
29
#### Usage Examples
30
31
**Known Total (Definite Mode)**:
32
```python
33
with alive_bar(1000, title='Processing Items') as bar:
34
for i in range(1000):
35
# do work
36
bar() # advance by 1
37
38
# Or advance by different amounts
39
for batch in batches:
40
process_batch(batch)
41
bar(len(batch)) # advance by batch size
42
```
43
44
**Unknown Total (Unknown Mode)**:
45
```python
46
with alive_bar(title='Processing') as bar:
47
for item in some_generator():
48
process_item(item)
49
bar() # increment counter
50
```
51
52
**Manual Percentage Mode**:
53
```python
54
with alive_bar(manual=True, title='Processing') as bar:
55
for i, item in enumerate(items):
56
process_item(item)
57
bar(i / len(items)) # set percentage directly
58
```
59
60
### Alive Iterator Adapter
61
62
Wraps iterables to automatically track progress without manual bar() calls. Infers total from iterable length when possible and provides the same bar handle interface.
63
64
```python { .api }
65
def alive_it(it: Collection[T], total: Optional[int] = None, *,
66
finalize: Callable[[Any], None] = None,
67
calibrate: Optional[int] = None, **options: Any) -> Iterable[T]:
68
"""
69
Iterator adapter that automatically tracks progress.
70
71
Parameters:
72
- it: Input iterable to be processed
73
- total (Optional[int]): Override total count (use 0 to force unknown mode)
74
- finalize (Optional[Callable]): Function called when iteration completes
75
- calibrate (Optional[int]): Maximum theoretical throughput for animation calibration
76
- **options: Configuration options (see Configuration documentation)
77
78
Returns:
79
Generator that yields items from input iterable
80
81
Raises:
82
- UserWarning: If manual=True is specified (not supported in iterator mode)
83
"""
84
```
85
86
#### Usage Examples
87
88
**Basic Iterator Adaptation**:
89
```python
90
items = range(1000)
91
for item in alive_it(items, title='Processing'):
92
process_item(item)
93
# Progress automatically tracked
94
```
95
96
**With Finalization Callback**:
97
```python
98
def finalize_processing(bar):
99
bar.title = 'Processing Complete'
100
bar.text = f'Processed {bar.current} items'
101
102
for item in alive_it(items, finalize=finalize_processing, receipt_text=True):
103
process_item(item)
104
```
105
106
**Force Unknown Mode**:
107
```python
108
# Even if iterable has length, force unknown mode
109
for item in alive_it(items, total=0):
110
process_item(item)
111
```
112
113
### Bar Handle Interface
114
115
The object returned by alive_bar context manager, providing methods and properties for controlling the progress bar.
116
117
#### Callable Interface
118
119
```python { .api }
120
def __call__(self, count: int = 1, *, skipped: bool = False) -> None:
121
"""
122
Advance the progress bar.
123
124
Parameters:
125
- count (int): Amount to advance (can be negative in definite mode)
126
- skipped (bool): Whether this count represents skipped items (for resumption)
127
"""
128
```
129
130
**Usage Examples**:
131
```python
132
with alive_bar(1000) as bar:
133
# Advance by 1 (default)
134
bar()
135
136
# Advance by specific amount
137
bar(50)
138
139
# Skip already processed items (for resumption)
140
bar(100, skipped=True)
141
142
# Go backwards (definite mode only)
143
bar(-10)
144
```
145
146
#### Read-Only Properties
147
148
```python { .api }
149
@property
150
def current(self) -> Union[int, float]:
151
"""Current count or percentage value."""
152
153
@property
154
def monitor(self) -> str:
155
"""Current monitor text (formatted count/total/percent)."""
156
157
@property
158
def rate(self) -> str:
159
"""Current processing rate text."""
160
161
@property
162
def eta(self) -> str:
163
"""Current ETA (Estimated Time of Arrival) text."""
164
165
@property
166
def elapsed(self) -> float:
167
"""Elapsed time in seconds since bar started."""
168
169
@property
170
def receipt(self) -> str:
171
"""Final receipt string (available even after completion)."""
172
```
173
174
#### Assignable Properties
175
176
```python { .api }
177
@property
178
def text(self) -> Optional[str]:
179
"""Situational message displayed within or below the bar."""
180
181
@text.setter
182
def text(self, value: Optional[str]) -> None:
183
"""Set situational message."""
184
185
@property
186
def title(self) -> Optional[str]:
187
"""Bar title (can be changed even after completion)."""
188
189
@title.setter
190
def title(self, value: Optional[str]) -> None:
191
"""Set bar title."""
192
```
193
194
**Usage Examples**:
195
```python
196
with alive_bar(1000, title='Initial Title') as bar:
197
for i in range(1000):
198
bar.text = f'Processing item {i}'
199
process_item(i)
200
bar()
201
202
# Change title even after completion
203
bar.title = 'Processing Complete'
204
```
205
206
#### Methods
207
208
```python { .api }
209
def pause(self):
210
"""
211
Context manager to pause the progress bar.
212
213
Temporarily stops the bar, clears the display, and returns control
214
to the Python prompt. Resumes seamlessly when context exits.
215
216
Returns:
217
Context manager for pausing the bar
218
"""
219
```
220
221
**Usage Example**:
222
```python
223
with alive_bar(1000) as bar:
224
for i in range(500):
225
process_item(i)
226
bar()
227
228
# Pause for manual intervention
229
with bar.pause():
230
print("Bar is paused - doing manual work")
231
manual_fixes()
232
input("Press Enter to continue...")
233
234
# Bar resumes automatically
235
for i in range(500, 1000):
236
process_item(i)
237
bar()
238
```
239
240
### Resumption Support
241
242
Support for resuming long-running processes by marking already-processed items as skipped, preventing ETA calculation issues.
243
244
#### Skipped Items Pattern
245
246
```python
247
# Resume from known position
248
with alive_bar(10000) as bar:
249
bar(5000, skipped=True) # Mark first 5000 as already done
250
for i in range(5000, 10000):
251
process_item(i)
252
bar()
253
254
# Resume with scattered completion
255
processed_items = get_already_processed()
256
with alive_bar(len(all_items)) as bar:
257
for item in all_items:
258
if item.id in processed_items:
259
bar(skipped=True)
260
continue
261
262
process_item(item)
263
bar()
264
```
265
266
### Modes of Operation
267
268
#### Definite Mode (with total)
269
- Displays progress as count/total and percentage
270
- Calculates accurate ETA based on remaining work
271
- Supports negative increments and resumption
272
- Shows warning if final count doesn't match expected total
273
274
#### Unknown Mode (without total)
275
- Displays only current count
276
- Shows processing rate but no ETA
277
- Useful for generators or streams of unknown size
278
279
#### Manual Mode
280
- Accept percentage values directly instead of counts
281
- Useful when progress calculation is complex
282
- Cannot be used with alive_it iterator adapter
283
284
### Error Handling
285
286
```python
287
# Common exceptions
288
try:
289
with alive_bar("invalid") as bar: # TypeError
290
pass
291
except TypeError as e:
292
print(f"Invalid total type: {e}")
293
294
try:
295
with alive_bar(100, invalid_option=True) as bar: # ValueError
296
pass
297
except ValueError as e:
298
print(f"Invalid configuration: {e}")
299
300
# Keyboard interruption
301
try:
302
with alive_bar(1000) as bar:
303
for i in range(1000):
304
bar()
305
except KeyboardInterrupt:
306
print("Processing interrupted by user")
307
```