Allow usage as a context manager.

This commit is contained in:
Tobias Gruetzmacher
2016-07-31 21:58:51 +02:00
parent 6553b7b207
commit 086cfd5599
3 changed files with 24 additions and 9 deletions

View File

@@ -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

View File

@@ -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()

View File

@@ -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):