2 python 进度条
Python 进度条的使用指南
Python 中常见的进度条库包括 tqdm、alive-progress 和 progressbar,每种库都有其特点。以下不仅详细介绍这些库,还会展示代码运行后的渲染效果,并补充 with 语句的用法。
方法 1:使用 tqdm 模块
tqdm 是最常用的进度条库,易用且功能强大。
安装
pip install tqdm
基本用法
from tqdm import tqdm
import time
for i in tqdm(range(100), desc="Processing"):
time.sleep(0.05) # 模拟耗时任务
效果渲染:
Processing: 100%|███████████████████████████████████| 100/100 [00:05<00:00, 20.00it/s]
结合 with 使用
with 语句可以更优雅地管理进度条的上下文,适合需要动态更新进度的任务。
from tqdm import tqdm
import time
with tqdm(total=100, desc="Downloading") as pbar:
for i in range(10):
time.sleep(0.5)
pbar.update(10) # 更新进度
效果渲染:
Downloading: 100%|███████████████████████████████████| 100/100 [00:05<00:00, 20.00it/s]
自定义样式
tqdm 提供灵活的自定义功能:
for i in tqdm(range(100), desc="Custom Progress", ncols=80, ascii=True, colour="green"):
time.sleep(0.05)
效果渲染:
Custom Progress: 100%|###############################################| 100/100 [00:05<00:00, 20.00it/s]
方法 2:使用 alive-progress 模块
alive-progress 以其美观和动态效果著称,支持高度定制化。
安装
pip install alive-progress
基本用法
from alive_progress import alive_bar
import time
with alive_bar(100, title="Processing") as bar:
for i in range(100):
time.sleep(0.05)
bar()
效果渲染:
Processing |███████████████████████████████████| 100/100 [100%] in 5.0s
自定义样式
可以通过 bar 和 spinner 参数自定义外观。
with alive_bar(100, bar="blocks", spinner="dots_reverse", title="Custom Task") as bar:
for i in range(100):
time.sleep(0.05)
bar()
效果渲染:
Custom Task |▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉| 100/100 [100%] in 5.0s
动态更新总数
data = ["task1", "task2", "task3"]
with alive_bar(len(data), title="Dynamic Task") as bar:
for task in data:
time.sleep(1)
bar()
方法 3:使用 progressbar 模块
progressbar 支持丰富的部件组合,可自定义多种风格。
安装
pip install progressbar2
基本用法
import progressbar
import time
with progressbar.ProgressBar(max_value=100) as bar:
for i in range(100):
time.sleep(0.05)
bar.update(i)
效果渲染:
72% (72 of 100) |############### | Elapsed Time: 0:03:36 ETA: 0:01:26
自定义格式
import progressbar
widgets = [
'Progress: ', progressbar.Percentage(),
' ', progressbar.Bar(marker='=', left='[', right=']'),
' ', progressbar.ETA(),
]
with progressbar.ProgressBar(max_value=100, widgets=widgets) as bar:
for i in range(100):
time.sleep(0.05)
bar.update(i)
效果渲染:
Progress: 72% [=====================> ] ETA: 0:00:28
方法 4:手动实现简单进度条
如果不依赖第三方库,可以用手动方式实现进度条。
import sys
import time
def simple_progress_bar(total, current):
bar_length = 50
progress = current / total
block = int(bar_length * progress)
bar = '#' * block + '-' * (bar_length - block)
sys.stdout.write(f"\r[{bar}] {current}/{total} ({progress * 100:.2f}%)")
sys.stdout.flush()
total = 100
for i in range(total):
time.sleep(0.05)
simple_progress_bar(total, i + 1)
print("\nDone!")
效果渲染:
[##########################################] 100/100 (100.00%)
Done!
总结
| 方法 | 优点 | 缺点 | 推荐场景 |
|---|---|---|---|
tqdm |
易用,支持多样化配置,性能较高 | 样式相对简单 | 通用进度条需求 |
alive-progress |
动态效果丰富,美观,配置灵活 | 功能比 tqdm 略少 |
更注重动态和美观的场景 |
progressbar |
组件丰富,可高度定制化 | 使用较复杂 | 需要复杂进度条场景 |
| 手动实现 | 无需额外依赖,完全可控 | 实现较复杂,不够美观 | 轻量化任务或学习使用 |
选择时根据需求和任务复杂度决定,推荐优先使用 tqdm 或 alive-progress。