Skip to content

Using Python package tqdm to display progress bar

Display Python code on the screen

Introduction

Sometimes, we want to be able to visualize the progress of our program, that is, to display a progress bar on the screen. It allows us to know the working status of the program.

Of course we can create the progress bar ourselves, or use a well-known package in Python: tqdm.

tqdm also means progress bar in Arabic, only need to install this Python package and we can use tqdm to display the progress wherever we need to iterate. Here is how to use tqdm.


How to use tqdm

Foundation

Since this package is not built-in Python package, if we use it for the first time, we need download it using the following command:

sudo pip3 install tqdm

After installation, let’s look at the sample code:

# -*- coding: utf-8 -*-
from time import sleep
from tqdm import tqdm, trange

for i in tqdm(range(1000)):
    sleep(0.01)


Output:

100%|██████████| 1000/1000 [00:10<00:00, 95.76it/s]

The sleep() function is to stop the program for 0.01 second each time it reaches here, a total of 1000 times. We can see that the output below has a progress bar. You can actually test it and you should see the progress bar grow.


trange()

In addition, we can also use trange() to achieve the same function.

for i in trange(1000):
    sleep(0.01)


Output:

100%|██████████| 1000/1000 [00:10<00:00, 95.72it/s]

This is also a method.


update()

In addition, not only is it used in the for loop, we can define when to advance the progress ourselves. The following is a simple example:

times = 0
progress = tqdm(total=1000)
while times < 1000:
    progress.update(1)
    times += 1
    sleep(0.01)


Output:

100%|██████████| 1000/1000 [00:10<00:00, 95.68it/s]

It seems to be the same function, but we can choose when to use progress.update() this time, or choose the number of update() ourselves.


Customize your own progress bar

In addition to using the tqdm module to implement your own progress bar, you can write your own progress bar. Let me give some advice and make everyone laugh:

from time import sleep

temp = 0
total = 1000

for n in range(1000):
    temp += 1
    print('\r' + '[Progress]:[%s%s]%.2f%%;' % (
    '█' * int(temp*20/total), ' ' * (20-int(temp*20/total)),
    float(temp/total*100)), end='')
    sleep(0.01)


Output:

[Progress]:[███████████████████]100.00%

If you are interested, you might as well write about your progress bar. The progress bar I wrote is relatively dead, and there is no way to choose the update time arbitrarily like tqdm-but this is also where we can modify it at will.


References


Read More

Leave a ReplyCancel reply

Click to Copy
Exit mobile version