Plenty of operations, such as web scraping, data processing, or file upload may require some time to finish.
Providing a loading bar gives users insight into how much longer the operation will take, thus boosting the application’s usability. This tutorial describes how to implement such functionality in Python with the help of a tiny yet helpful library called tqdm.
Step 1: Install the tqdm library
If you don’t already have the tqdm library installed on your system, you can do so via pip. Run the following command in your terminal:
1 |
pip install tqdm |
The tqdm is a fast, extensible progress bar for Python and CLI. It helps you to visualize the progression of Python iterable execution.
Step 2: Using tqdm in your Python script
Once you have installed tqdm, you can easily use it in your Python script. Here’s an example:
1 2 3 4 5 6 7 |
from tqdm import tqdm import time for i in tqdm(range(100)): # This will be the operation you want to observe progress for # For demonstration, we just sleep for a short time time.sleep(0.1) |
Here, tqdm will automatically generate and update a console-based loading bar as your loop iterates through the desired range. The sleep command represents the task that should take a while to complete.
Step 3: Customizing the tqdm progress bar
tqdm is highly customizable. You can change the descriptions, units, and even the visual elements of the progress bar.
1 2 3 4 5 6 |
from tqdm import tqdm import time # Adding a description and units for i in tqdm(range(100), desc="Processing items", unit="item"): time.sleep(0.1) |
This code will configure the tqdm loading bar to display progress as “item” units processed under the description “Processing items”. Experiment by configuring it according to your requirements.
Full Code:
1 2 3 4 5 6 |
from tqdm import tqdm import time # Adding a description and units for i in tqdm(range(100), desc="Processing items", unit="item"): time.sleep(0.1) |
Conclusion:
In this tutorial, we have learned how to show a loading or progress bar in Python using the tqdm library. Progress bars are a great way to keep track of your tasks, operations, or loops in real-time and add a nice touch to your Python applications. Don’t hesitate to dive into the official tqdm documentation for more possibilities and customizations.