运行程序的时候,即不想看那些快速飘过的日志信息,又不想只让光标在那闪,怎么办呢?加个进度条吧
tqdm
tqdm是Python的一个进度条库,使用起来非常方便,上手十分容易
最简单的方式是使用tqdm包裹一个迭代器,迭代器现在所处的进度就是后面显示的进度。
基于迭代的使用
tqdm可以包裹任何迭代器,显示的进度就是当前迭代的进度1
2
3text = ""
for char in tqdm(["a", "b", "c", "d"]):
text = text + char
手动操作
通过with来控制tqdm()的更新:1
2
3with tqdm(total=100) as pbar:
for i in range(10):
pbar.update(10)
或者不使用with,使用一个变量来表示,但是最后不要忘了撤销close()1
2
3
4pbar = tqdm(total=100)
for i in range(10):
pbar.update(10)
pbar.close()
模块
tqdm还可以使用在shell的管道命令中,在标准输入和标准输出中添加1
2
3
4
5
6
7
8
9
10
11
12
13
14$ time find . -name '*.py' -exec cat \{} \; | wc -l
857365
real 0m3.458s
user 0m0.274s
sys 0m3.325s
$ time find . -name '*.py' -exec cat \{} \; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365
real 0m3.585s
user 0m0.862s
sys 0m3.358s