【Python 实战】别再傻傻等!用 tqdm 一行代码给程序加“进度条外挂”
0x00 前言:为什么你总是盯着黑屏发呆?
在跑深度学习训练、爬大批量网页或者批量处理文件时,最痛苦的不是代码报错,而是不知道程序跑到哪儿了。
一个训练 epoch 跑了 20 min 还是 2 h?爬虫 10 w 条数据到底爬完没?没有进度条,就像下载文件看不到百分比,分分钟想 Alt+F4。
今天带来 Python 圈最香的进度条库——tqdm(taqadum,阿拉伯语“进度”),让你用一行代码把黑盒程序变“透明”。
0x01 30 秒极速上手
1.1 安装
pip install -U tqdm
1.2 Hello tqdm
from tqdm import tqdm
import time
for i in tqdm(range(100)):
time.sleep(0.01) # 假装很忙
运行效果:
100%|████████████| 100/100 [00:01<00:00, 98.12it/s]
一行代码,进度、速度、ETA 全都有!比 print(i) 优雅 1w 倍。
0x02 核心姿势大全
2.1 对可迭代对象无脑包一层
from tqdm import tqdm
for item in tqdm(my_list):
...
2.2 手动更新进度(适合 while/复杂逻辑)
with tqdm(total=1000) as pbar:
for chunk in read_chunks():
process(chunk)
pbar.update(len(chunk))
2.3 给 tqdm 加描述,告别“这是哪一步?”
pbar = tqdm(dataloader, desc='Training', ncols=100)
for x, y in pbar:
loss = train_step(x, y)
pbar.set_postfix(loss=f'{loss:.4f}')
效果:
Training: 45%|████▌ | 450/1000 [00:21<00:26, 20.81it/s, loss=0.1234]
0x03 进阶骚操作
3.1 多进度条并行(多线程/多进程)
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
urls = [...] * 1000
with ThreadPoolExecutor(max_workers=32) as ex, tqdm(total=len(urls)) as pbar:
def fetch(u):
requests.get(u)
pbar.update()
list(ex.map(fetch, urls))
3.2 tqdm + pandas,DataFrame.apply 实时进度
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
df['new'] = df['col'].progress_apply(lambda x: heavy_func(x))
3.3 写入日志文件,再也不丢进度
from tqdm import tqdm
with tqdm(total=100, file=open('progress.log', 'w')) as pbar:
...
0x04 踩坑 & 调优
| 问题 | 原因 | 解法 |
|---|---|---|
| Notebook 里进度条疯狂刷屏 | 没选对前端 | from tqdm.notebook import tqdm |
| 进度条被 print 打断 | print 和 tqdm 互斥 | tqdm.write('msg') |
| 速度单位默认 it/s 不直观 | 自定义 unit | tqdm(..., unit='img') |
0x05 实战:把 10 万文件批量压缩并加密
import os, zipfile, tqdm
from cryptography.fernet import Fernet
key = Fernet.generate_key()
fernet = Fernet(key)
files = [f for f in os.listdir('imgs') if f.endswith('.jpg')]
with zipfile.ZipFile('imgs.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
for fname in tqdm(files, desc='Zipping & Encrypting', unit='file'):
full = os.path.join('imgs', fname)
with open(full, 'rb') as img:
data = fernet.encrypt(img.read())
zf.writestr(fname, data)
print('All done, key =', key.decode())
0x06 总结
| 场景 | 推荐用法 |
|---|---|
| for 循环 | for x in tqdm(seq): |
| 手动更新 | tqdm.update() |
| pandas | tqdm.pandas() |
| 多线程 | concurrent.futures + tqdm |
| Notebook | tqdm.notebook |
tqdm 把“进度可视化”做成了基础设施,写脚本时顺手包一层,既提升体验也减少焦虑。下次别再让 CPU 默默跑断腿,而你只能对着黑屏发呆!
0x07 参考资料
- 官方仓库:https://github.com/tqdm/tqdm
- 官方文档:https://tqdm.github.io/docs/tqdm/
- 进阶技巧:https://tqdm.github.io/tqdm-cookbook/
- Python制作进度条,18种方式全网最全!(不全去你家扫厕所!)
如果本文帮到了你,记得点个赞 👍 再走!有任何问题评论区见~
6439

被折叠的 条评论
为什么被折叠?



