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
I like Brian Khuu's answer for its simplicity and not needing external packages. I changed it a bit so I'm adding my version here:
import sys
import time
def updt(total, progress):
"""
Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}".format(
"#" * block + "-" * (barLength - block), round(progress * 100, 0),
status)
sys.stdout.write(text)
sys.stdout.flush()
runs = 300
for run_num in range(runs):
time.sleep(.1)
updt(runs, run_num + 1)
It takes the total number of runs (total
) and the number of runs processed so far (progress
) assuming total >= progress
. The result looks like this:
[#####---------------] 27%