How to create a simple progress bars in Python
By Tan Lee Published on Feb 12, 2024 380
First, you need to install the tqdm package by typing this line in your terminal
->pip install tqdm
You can use tqdm
to wrap any iterable (e.g., list, range) and display a progress bar as it iterates through the items.
Next, type type this code below in your editor
from tqdm import tqdm import time # Example: Progress bar for a loop for i in tqdm(range(10)): time.sleep(0.5) # Simulate a task that takes time
In this example:
tqdm(range(10))
: This creates a progress bar that updates as the loop progresses through the range of 10 numbers.time.sleep(0.5)
: Simulates a task taking time (like a network request or computation).
When you run the code, you'll see a progress bar like this in the terminal:
100%|██████████| 10/10 [00:05<00:00, 2.00it/s]
You can also add a custom description to your progress bar:
for i in tqdm(range(10), desc="Processing items"): time.sleep(0.5)
This will show Processing items
before the progress bar.
If you have nested loops and want a progress bar for each, you can use tqdm
with nested
:
from tqdm import tqdm for i in tqdm(range(5), desc="Outer loop"): for j in tqdm(range(10), desc="Inner loop", leave=False): time.sleep(0.1)
This shows a progress bar for both the outer and inner loops.
Another way you can use alive-progress, this is the coolest progress bar ever
->pip install alive-progress
Next, Open your editor then enter the code below
from alive_progress.styles import showtime showtime()
If you don't want to use external packages, you can handle your code by customizing the bar progress symbol "#", bar size, text prefix etc.
Python 3.6+
import sys import time def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+ count = len(it) start = time.time() def show(j): x = int(size*j/count) remaining = ((time.time() - start) / j) * (count - j) mins, sec = divmod(remaining, 60) time_str = f"{int(mins):02}:{sec:05.2f}" print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count} Est wait {time_str}", end='\r', file=out, flush=True) for i, item in enumerate(it): yield item show(i+1) print("\n", flush=True, file=out)
[████████████████████████████.........................] 24/50 Est wait 00:05.38
or usage
import time for i in progressbar(range(15), "Computing: ", 40): time.sleep(0.1) # your handle code
Python 3.3+
import sys def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.3+ count = len(it) def show(j): x = int(size*j/count) print("{}[{}{}] {}/{}".format(prefix, "#"*x, "."*(size-x), j, count), end='\r', file=out, flush=True) show(0) for i, item in enumerate(it): yield item show(i+1) print("\n", flush=True, file=out)
Python 2 (old version)
import sys def progressbar(it, prefix="", size=60, out=sys.stdout): count = len(it) def show(j): x = int(size*j/count) out.write("%s[%s%s] %i/%i\r" % (prefix, u"#"*x, "."*(size-x), j, count)) out.flush() show(0) for i, item in enumerate(it): yield item show(i+1) out.write("\n") out.flush()
I also found a simple function that displays a progress with Python
To use it, just copy the lines in "def update_progress(progress)". Don't forget to import sys. Call it whenever you need to display or update the progress bar.
This works by sending the "\r" symbol directly to the console to move the cursor back to the starting point. "in" in python does not recognize the above symbol for this purpose, hence we need 'sys'
import time, sys # update_progress() : Displays or updates a console progress bar ## Accepts a float between 0 and 1. Any int will be converted to a float. ## A value under 0 represents a 'halt'. ## A value at 1 or bigger represents 100% def update_progress(progress): barLength = 10 # Modify this to change the length of the progress bar status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status) sys.stdout.write(text) sys.stdout.flush() # update_progress test script print "progress : 'hello'" update_progress("hello") time.sleep(1) print "progress : 3" update_progress(3) time.sleep(1) print "progress : [23]" update_progress([23]) time.sleep(1) print "" print "progress : -10" update_progress(-10) time.sleep(2) print "" print "progress : 10" update_progress(10) time.sleep(2) print "" print "progress : 0->1" for i in range(101): time.sleep(0.1) update_progress(i/100.0) print "" print "Test completed" time.sleep(10)
When you execute the program you can see it as show below
progress : 'hello'
Percent: [----------] 0% error: progress var must be float
progress : 3
Percent: [##########] 100% Done...
progress : [23]
Percent: [----------] 0% error: progress var must be float
progress : -10
Percent: [----------] 0% Halt...
progress : 10
Percent: [##########] 100% Done...
progress : 0->1
Percent: [##########] 100% Done...
Test completed