How to Show Progress Bar In Python?
Let’s have a look at tqdm
Python package which helps in showing progress bar in Python and CLI.
Show Progress Bar
I’m having Python 2.7.18
installed in my system. You can install the tqdm
package using pip
.
pip install tqdm
Once it’s installed let’s create a file called app.py
and import the tqdm
package.
from tqdm import tqdm
To show some time delay, let’s import the sleep
package from time
module.
from time import sleep
Now, I’ll simply iterate from 0 to 9 and introduce a delay of 1 sec between each iteration.
from tqdm import tqdm
from time import sleep
for i in tqdm(range(10)):
sleep(1)
You should be able to see the progress bar.
C:\Users\Jay>python app.py
40%|###########2 | 4/10 [00:08<00:12, 2.11s/it]
Show Progress Bar in API Calls
Now let’s take a look at a real time scenario where I need to make a couple of API calls to get user information based on user id. Let’s see how you can use tqdm
to show progress bar in such scenario.
This time we won’t be using the sleep
method.
Import the requests method to make API calls.
import requests
I’ll using range for iterating over user ids 1 to 10.
progress = tqdm(range(1,11))
Now you can iterate over the progress
variable and make the API call.
for i in progress:
parseName(i)
Here is how the app.py
file looks :
from tqdm import tqdm
import requests
progress = tqdm(range(1,11))
def parseName(n):
progress.set_description("Processing user %s" % n)
response = requests.get('https://jsonplaceholder.typicode.com/users/'+str(n))
for i in progress:
parseName(i)
Save the change and run the Python program. You will be able to see the progress of each API call as shown:
C:\Users\Jay>python app.py
Processing user 7: 60%|#####3 | 6/10 [00:01<00:01, 3.55it/s]
For a detailed information on what all other functionalities tqdm
module provides, I recommend reading the official documentation.