mirror of
https://github.com/verigak/progress.git
synced 2025-12-08 19:33:24 +00:00
Merge pull request #29 from TobiX/contextmanager
Allow usage as a context manager.
This commit is contained in:
11
README.rst
11
README.rst
@@ -34,6 +34,17 @@ To use them, just call ``next`` to advance and ``finish`` to finish:
|
||||
bar.next()
|
||||
bar.finish()
|
||||
|
||||
or use any bar of this class as a context manager:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from progress.bar import Bar
|
||||
|
||||
with Bar('Processing', max=20) as bar:
|
||||
for i in range(20):
|
||||
# Do some work
|
||||
bar.next()
|
||||
|
||||
The result will be a bar like the following: ::
|
||||
|
||||
Processing |############# | 42/100
|
||||
|
||||
@@ -73,11 +73,16 @@ class Infinite(object):
|
||||
self.update()
|
||||
|
||||
def iter(self, it):
|
||||
try:
|
||||
with self:
|
||||
for x in it:
|
||||
yield x
|
||||
self.next()
|
||||
finally:
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.finish()
|
||||
|
||||
|
||||
@@ -119,9 +124,7 @@ class Progress(Infinite):
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
try:
|
||||
with self:
|
||||
for x in it:
|
||||
yield x
|
||||
self.next()
|
||||
finally:
|
||||
self.finish()
|
||||
|
||||
@@ -27,8 +27,9 @@ for bar_cls in (Bar, ChargingBar, FillingSquaresBar, FillingCirclesBar):
|
||||
|
||||
for bar_cls in (IncrementalBar, PixelBar, ShadyBar):
|
||||
suffix = '%(percent)d%% [%(elapsed_td)s / %(eta)d / %(eta_td)s]'
|
||||
bar = bar_cls(bar_cls.__name__, suffix=suffix)
|
||||
for i in bar.iter(range(200)):
|
||||
with bar_cls(bar_cls.__name__, suffix=suffix, max=200) as bar:
|
||||
for i in range(200):
|
||||
bar.next()
|
||||
sleep()
|
||||
|
||||
for spin in (Spinner, PieSpinner, MoonSpinner, LineSpinner, PixelSpinner):
|
||||
|
||||
Reference in New Issue
Block a user