When using the console app in Python, using click progressbar makes it nice to visualize the progress when working for a long time.
However, in some cases, when you put a function of the process that originally used progressbar in the server process or batch process, you may want to turn on / off the output of progressbar with an optional argument.
Here are some code patterns that can be used in such cases. => I found a technique to specify / dev / null for file
, so that is the first ...
import sys
import click
def something(items, show_progress=False):
out = sys.stdout if show_progress else open('/dev/null', 'wb')
with click.progressbar(items, file=out) as bar:
for item in bar:
'abcd' * (1024 * 10)
items = list(xrange(10000))
something(items, show_progress=True)
print '--------'
something(items, show_progress=False)
It seems that you can specify the output destination of click.progressbar
with the option file
, so if you specify a file object to write to / dev / null
, nothing will come out.
However, if you want to call a function like this something
thousands of times, you should close the properly opened file object.
import functools
from contextlib import contextmanager
import click
@contextmanager
def dummy_bar(items, **kwargs):
yield items
def something(items, show_progress=False):
f = click.progressbar if show_progress else dummy_bar
fbar = functools.partial(f, items, show_pos=True, show_eta=True)
with fbar() as bar:
for item in bar:
'abcd' * (1024 * 10)
items = list(xrange(10000))
something(items, show_progress=True)
print '--------'
something(items, show_progress=False)
I defined a function called dummy_bar
to create a bar that doesn't output anything.
Since click.progressbar
is called with the with
clause, it is assigned to the variable after ʻasusing contextmanager, that is, iterable given as an argument is returned as it is with
yield`. ..
The function to be used is switched with the show_progress
option, and the arguments are partially applied in functools.partial
so that they can be called uniformly without arguments.
So, where it was originally with click.progressbar (...
, it is simply with fbar ()
.
Now the bar
according to the behavior of the option is assigned by ʻas, and the rest is ok if you use it like
click.progressbar` normally.
Recommended Posts