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
Here's a short solution that builds the loading bar programmatically (you must decide how long you want it).
import time
n = 33 # or however many loading slots you want to have
load = 0.01 # artificial loading time!
loading = '.' * n # for strings, * is the repeat operator
for i in range(n+1):
# this loop replaces each dot with a hash!
print('\r%s Loading at %3d percent!' % (loading, i*100/n), end='')
loading = loading[:i] + '#' + loading[i+1:]
time.sleep(load)
It is quite straightforward in Python3:
import time
import math
def show_progress_bar(bar_length, completed, total):
bar_length_unit_value = (total / bar_length)
completed_bar_part = math.ceil(completed / bar_length_unit_value)
progress = "*" * completed_bar_part
remaining = " " * (bar_length - completed_bar_part)
percent_done = "%.2f" % ((completed / total) * 100)
print(f'[{progress}{remaining}] {percent_done}%', end='\r')
bar_length = 30
total = 100
for i in range(0, total + 1):
show_progress_bar(bar_length, i, total)
time.sleep(0.1)
print('\n')
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.
Use this library: fish (GitHub).
Usage:
>>> import fish
>>> while churning:
... churn_churn()
... fish.animate()
Have fun!
A very simple approach:
def progbar(count: int) -> None:
for i in range(count):
print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="\r")
yield i
print('\n')
And the usage:
from time import sleep
for i in progbar(10):
sleep(0.2) #whatever task you need to do
With tqdm (conda install tqdm or pip install tqdm) you can add a progress meter to your loops in a second:
from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
sleep(3)
60%|██████ | 6/10 [00:18<00:12, 0.33 it/s]
Also, there is a notebook version:
from tqdm.notebook import tqdm
for i in tqdm(range(100)):
sleep(3)
You can use tqdm.auto instead of tqdm.notebook to work in both a terminal and notebooks.
tqdm.contrib contains some helper functions to do things like enumerate, map, and zip. There are concurrent maps in tqdm.contrib.concurrent.
You can even get progress sent to your phone after disconnecting from a jupyter notebook using tqdm.contrib.telegram or tqdm.contrib.discord.
