tqdm Helps You Save Time
Made by Mike_Zhang
Unfold Python Topics $\triangledown$
Intro
「时间就是金钱,效率就是生命」
在编写和运行Python程序时,我们常常想知道运行完成的预计时间,以便更好地安排时间,如:
1 |
|
在这种情况下,我们可以使用Python的tqdm
库来显示进度条,以便更好地了解程序的运行情况,如:
- 记录已经完成的任务数量/任务时间
- 预计完成时间
- 记录运行速度
- …
tqdm
Usage
1. Installation
https://github.com/tqdm/tqdm?tab=readme-ov-file#installation
1.1 via pip
1 |
|
https://pypi.org/project/tqdm/
1.2 via conda
1 |
|
2. Using
2.1 Automatically update
1 |
|
Output:
1 |
|
2.2 Manually update
If you want to update the progress bar manually, you can use the following code:
1 |
|
Output:
1 |
|
2.3 Advanced Usage
2.3.1 Set description and postfix
1 |
|
Output:
1 |
|
2.3.2 Set width of the progress bar
To fit the progress bar in the terminal, you can set the width of the progress bar:
1 |
|
ncols=100
:
1 |
|
ncols=80
:
1 |
|
ncols=60
:
1 |
|
2.3.3 Printing during the progress bar
If you use print()
during the progress bar, the progress bar will be interrupted, like:
1 |
|
Output:
1 |
|
To avoid this, you can use pbar.write()
instead of print()
:
1 |
|
Output:
1 |
|
where the progress bar will always be displayed at the bottom of the terminal and the text will be displayed above the progress bar.
2.3.4 Color, position and nested progress bars
If you want to display nested progress bars, you can use the following code:1
2
3
4
5
6from tqdm import tqdm
import time
for i in tqdm(range(2), desc="[Split]", ncols=80, leave=False, colour="green"):
for j in tqdm(range(5), desc="[Epoch]", ncols=80, leave=False, colour="blue"):
for k in tqdm(range(10), desc="[Batch]", ncols=80, leave=False, colour="red"):
time.sleep(0.1)
Output:
Where leave=False
arranges the position of the progress bar, and colour
sets the color of the progress bar.
You can find more parameters and examples in the official documentation here.
References
“tqdm/tqdm: A Fast, Extensible Progress Bar for Python and CLI” GitHub, 2025. https://github.com/tqdm/tqdm.
Outro
最后,你知道tqdm
是什么的缩写吗?代表了什么意思呢?请在下方留言,分享你的看法。
原创文章,转载请标明出处
Made by Mike_Zhang