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.next()
|
||||||
bar.finish()
|
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: ::
|
The result will be a bar like the following: ::
|
||||||
|
|
||||||
Processing |############# | 42/100
|
Processing |############# | 42/100
|
||||||
|
|||||||
@@ -73,12 +73,17 @@ class Infinite(object):
|
|||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
def iter(self, it):
|
def iter(self, it):
|
||||||
try:
|
with self:
|
||||||
for x in it:
|
for x in it:
|
||||||
yield x
|
yield x
|
||||||
self.next()
|
self.next()
|
||||||
finally:
|
|
||||||
self.finish()
|
def __enter__(self):
|
||||||
|
self.start()
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
self.finish()
|
||||||
|
|
||||||
|
|
||||||
class Progress(Infinite):
|
class Progress(Infinite):
|
||||||
@@ -119,9 +124,7 @@ class Progress(Infinite):
|
|||||||
except TypeError:
|
except TypeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
with self:
|
||||||
for x in it:
|
for x in it:
|
||||||
yield x
|
yield x
|
||||||
self.next()
|
self.next()
|
||||||
finally:
|
|
||||||
self.finish()
|
|
||||||
|
|||||||
@@ -27,9 +27,10 @@ for bar_cls in (Bar, ChargingBar, FillingSquaresBar, FillingCirclesBar):
|
|||||||
|
|
||||||
for bar_cls in (IncrementalBar, PixelBar, ShadyBar):
|
for bar_cls in (IncrementalBar, PixelBar, ShadyBar):
|
||||||
suffix = '%(percent)d%% [%(elapsed_td)s / %(eta)d / %(eta_td)s]'
|
suffix = '%(percent)d%% [%(elapsed_td)s / %(eta)d / %(eta_td)s]'
|
||||||
bar = bar_cls(bar_cls.__name__, suffix=suffix)
|
with bar_cls(bar_cls.__name__, suffix=suffix, max=200) as bar:
|
||||||
for i in bar.iter(range(200)):
|
for i in range(200):
|
||||||
sleep()
|
bar.next()
|
||||||
|
sleep()
|
||||||
|
|
||||||
for spin in (Spinner, PieSpinner, MoonSpinner, LineSpinner, PixelSpinner):
|
for spin in (Spinner, PieSpinner, MoonSpinner, LineSpinner, PixelSpinner):
|
||||||
for i in spin(spin.__name__ + ' ').iter(range(100)):
|
for i in spin(spin.__name__ + ' ').iter(range(100)):
|
||||||
|
|||||||
Reference in New Issue
Block a user