用Python给你的代码上个进度条吧,代码也要面子的!
最近在跑一些代码的时候,很烦。。。
因为有时候不知道这段程序什么时候能执行完,现在执行哪里了,如果报错或者二进入死循环,那不是非常的浪费时间。
因此,我在想到底该怎么办才能知道这些,就开始找,原来可以直接加入一个——进度条,发现有些代码很长,而有些有很简洁,但是简洁到,我都不知道如何去应用到自己的实际中,那还有什么用。代码实现与应用
准备工作
1.导入包——tqdm
tqdm简介:Tqdm 是 Python 进度条库
为了便于看效果,这里导入一个time库,用于延迟
代码展示
<pre class="ql-align-justify" style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from tqdm import tqdm
import time
for i in tqdm(range(365)):
time.sleep(0.2)
</pre>
12%|█▏ | 45/365 [00:09<01:04, 4.99it/s]
因此我要如何使用?
1.含有处理文件个数的情况
对于程序中有循环的地方,可以直接将range(365)替换成你的处理的文件个数
2.不含文件个数信息的情况
同意的只要满足是可迭代的便可以加入进度条,感觉天秀
<pre class="ql-align-justify" style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from tqdm import tqdm
import time
for i in tqdm(range(365)):
time.sleep(0.2)
for i in tqdm(['happy','new','year']):
time.sleep(1.5)
# 对元祖类型可行
for i in tqdm(('happy','new','year')):
time.sleep(1.5)
字典类型可行
for i in tqdm({'year':2019,'month':1,'day':3}):
time.sleep(1.5)
</pre>
100%|██████████| 3/3 [00:04<00:00, 1.50s/it]