[python] option to turn off the output of click.progressbar

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

A simple way to use on UNIX

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.

How to solve with Python technique that can be used even in environment without / dev / null

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)

Commentary

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 withyield`. ..

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

[python] option to turn off the output of click.progressbar
I want to output the beginning of the next month with Python
Output the contents of ~ .xlsx in the folder to HTML with Python
Output the number of CPU cores in Python
Setting to output the log of cron execution
How to erase the characters output by Python
Output in the form of a python array
the zen of Python
Basics of python: Output
Easy way to check the source of Python modules
The wall of changing the Django service from Python 2.7 to Python 3
Template of python script to read the contents of the file
How to get the number of digits in Python
[Python] Summary of how to specify the color of the figure
14 quizzes to understand the surprisingly confusing scope of Python
[Introduction to Python] Basic usage of the library matplotlib
[Python] How to output the list values in order
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Completely translated the site of "The Hitchhiker's Guide to Python"
Python Note: The mystery of assigning a variable to a variable
I tried to summarize the string operations of Python
Output the specified table of Oracle database in Python to Excel for each file
Towards the retirement of Python2
About the ease of Python
Turn off the brew warning
Filter the output of tracemalloc
About the features of Python
The Power of Pandas: Python
I tried to find the entropy of the image with python
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
Try to get the function list of Python> os package
Output "Draw ferns programmatically" to the drawing process in Python
Make the display of Python module exceptions easier to understand
Change the standard output destination to a file in Python
The story of introducing jedi (python auto-completion package) to emacs
[Python] I want to use the -h option with argparse
[Python] I tried to visualize the follow relationship of Twitter
Try to automate the operation of network devices with Python
Debug by attaching to the Python process of the SSH destination
I want to know the features of Python and pip
Keras I want to get the output of any layer !!
Get the source of the page to load infinitely with python.
The story that the version of python 3.7.7 was not adapted to Heroku
Leave the troublesome processing to Python
The story of Python and the story of NaN
How to determine the existence of a selenium element in Python
How to change the log level of Azure SDK for Python
First Python 3 ~ The beginning of repetition ~
How to know the internal structure of an object in Python
Easy way to round off to the nearest whole number with python3
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
[Python] Try to graph from the image of Ring Fit [OCR]
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
[Introduction to Python] I compared the naming conventions of C # and Python.
Output to csv file with Python
Existence from the viewpoint of Python
[Python] How to get the first and last days of the month
First python ② Try to write code while examining the features of python
pyenv-change the python version of virtualenv
Read the standard output of a subprocess line by line in Python