How do I use a progress bar when my script is doing some task that is likely to take time?
For example, a function which takes some time to complete and returns True
when done. How can I display a progress bar during the time the function is being executed?
Note that I need this to be in real time, so I can't figure out what to do about it. Do I need a thread
for this? I have no idea.
Right now I am not printing anything while the function is being executed, however a progress bar would be nice. Also I am more interested in how this can be done from a code point of view.
Try progress from https://pypi.python.org/pypi/progress.
The result will be a bar like the following:
Here's a short solution that builds the loading bar programmatically (you must decide how long you want it).
It is quite straightforward in Python3:
Try PyProg. PyProg is an open-source library for Python to create super customizable progress indicators & bars.
It is currently at version 1.0.2; it is hosted on Github and available on PyPI (Links down below). It is compatible with Python 3 & 2 and it can also be used with Qt Console.
It is really easy to use. The following code:
will produce:
I actually made PyProg because I needed a simple but super customizable progress bar library. You can easily install it with:
pip install pyprog
.PyProg Github: https://github.com/Bill13579/pyprog
PyPI: https://pypi.python.org/pypi/pyprog/
Many of the answers above rely on external packages, but I also think (as some above stated) that most people just want a ready-made solution. The code below can be adapted to fit your needs by customizing the string part.
It is simpler and works without the need of a second thread to update the bar. Some packages above do that. A second thread can be a problem, for an ipython notebook, for example.
The code below only works with iterators that provide a length (i.e. len(iterator) must be defined).
Example:
Output:
...
...
it
can be any iterable object with alen
, e.g. ['a', 'b', 'c']` works just fine.You should link the progress bar to the task at hand (so that it measures the progress :D). For example, if you are FTPing a file, you can tell ftplib to grab a certain size buffer, let's say 128K, and then you add to your progress bar whatever percentage of the filesize 128k represents. If you are using the CLI, and your progress meter is 20 characters long, you would add one character when 1/20th of the file had transferred.