Python: How to add Progress Bar in Console with Examples


To add a progress bar in the console for a Python program we need to make use of the tqdm module - the most rich and famous python progress bar library.

Make sure to get the tqdm module downloaded using the pip installer.

pip install tqdm

Details:

pip show tqdm

Name: tqdm
Version: 4.65.0
Summary: Fast, Extensible Progress Meter
Home-page: https://tqdm.github.io
Author: 
Author-email: 
License: MPLv2.0, MIT Licences
Location: /opt/homebrew/lib/python3.11/site-packages
Requires: 
Required-by: spacy

Example 1: using for loop and time.sleep function

from tqdm import tqdm
import time

for i in tqdm(range(5)):
    time.sleep(1)
Demo of the progress bar in jupyter notebook (Google Colab):
Python Progress bar Example using for loop

Example 2: Progress bar while loop

from tqdm import tqdm
import time

total_iterations = 5
progress_bar = tqdm(total=total_iterations, desc="Progress", bar_format="{l_bar}{bar}{r_bar}")

iteration = 0
while iteration < total_iterations:
    time.sleep(1)
    progress_bar.update(1)
    iteration += 1

progress_bar.close()
Output:
Progress:   0%|          | 0/5 [00:00<?, ?it/s]
Progress:  20%|โ–ˆโ–ˆ        | 1/5 [00:01<00:04,  1.00s/it]
Progress:  40%|โ–ˆโ–ˆโ–ˆโ–ˆ      | 2/5 [00:02<00:03,  1.00s/it]
Progress:  60%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ    | 3/5 [00:03<00:02,  1.00s/it]
Progress:  80%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ  | 4/5 [00:04<00:01,  1.01s/it]
Progress: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 5/5 [00:05<00:00,  1.01s/it]

There is a lot you can do with the progress bar like setting the bar height, width, multiprocessing, changing color, text, and animation, for that you can follow the documentation on GitHub.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap