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.
There are specific libraries (like this one here) but maybe something very simple would do:
import time
import sys
toolbar_width = 40
# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("]\n") # this ends the progress bar
Note: progressbar2 is a fork of progressbar which hasn't been maintained in years.
With tqdm you can add a progress meter to your loops in a second:
In [1]: import time
In [2]: from tqdm import tqdm
In [3]: for i in tqdm(range(10)):
....: time.sleep(3)
60%|██████ | 6/10 [00:18<00:12, 0.33 it/s]
Also, there is a graphical version of tqdm since v2.0.0
(d977a0c
):
In [1]: import time
In [2]: from tqdm import tqdm_gui
In [3]: for i in tqdm_gui(range(100)):
....: time.sleep(3)
But be careful, since tqdm_gui
can raise a TqdmExperimentalWarning: GUI is experimental/alpha
, you can ignore it by using warnings.simplefilter("ignore")
, but it will ignore all warnings in your code after that.