如何让python代码显示进度信息?

版权声明:禁止转载至其它平台,转载至博客需带上此文链接。 https://blog.csdn.net/qq_41841569/article/details/86535843

今天在知乎上看问题看到有人问如何展示程序进度,之前我在写爬虫好像都是自己使用print来显示进度,对于自己写的代码我还是很熟悉的,没啥问题。但是当我们把代码交给其他人使用,如果有进度条显示会更友好一些。tqdm是一个小巧、可扩展的进度条python库,在github的star数高达8K。

学习Python中有不明白推荐加入交流群
                号:960410445
                群里有志同道合的小伙伴,互帮互助,
                群里有不错的视频学习教程和PDF!

image

image

安装

在命令行中的安装命令

pip install tqdm

在jupyter notebeook的Cell中的安装命令

!pip install tqdm

一、使用

tqdm实现进度条效果有多重形式,最常用的就是下面给出的三种

1.1 基于可迭代对象

将可迭代对象放入 tqdm.tqdm函数中 , 可迭代对象长度为n,则进度条有n个进度。

from tqdm import tqdmimport time 

text = ""for char in tqdm(["a", "b"]):
    text = text + char
    time.sleep(0.5)
100%|██████████| 2/2 [00:01<00:00,  1.99it/s]
from tqdm import tqdmfor i in tqdm(range(4)):   
    pass
    time.sleep(0.5)
100%|██████████| 4/4 [00:02<00:00,  1.98it/s]

trange(i)是tqdm(range(i))的简化版

from tqdm import trangefor i in trange(5):
    pass
    time.sleep(0.5)
100%|██████████| 5/5 [00:02<00:00,  1.99it/s]

我们可以将进度条先实例化,再放到for循环体中,这样就可以做一些操作

pbar = tqdm(['a', 'b', 'c', 'd', 'e'])for char in pbar:
    pbar.set_description("程序进度 {}".format(char))
    time.sleep(0.5)
程序进度 e: 100%|██████████| 5/5 [00:02<00:00,  1.97it/s]

1.2 手动

from tqdm import tqdmwith tqdm(total=100) as pbar:
    for i in range(10): 
        pbar.update(1)  
        time.sleep(0.5)
 10%|█         | 10/100 [00:04<00:44,  2.04it/s]
from tqdm import tqdmwith tqdm(total=100) as pbar:
    for i in range(20): 
        pbar.update(1)  
        time.sleep(0.5)
 20%|██        | 20/100 [00:09<00:40,  1.99it/s]
from tqdm import tqdmwith tqdm(total=100) as pbar:
    for i in range(20): 
        pbar.update(2)  
        time.sleep(0.5)
 40%|████      | 40/100 [00:00<00:00, 129055.51it/s]

如果不适用with语句,我们记得在代码后close掉。

import time 

pbar = tqdm(total=100)for i in range(10):
    pbar.update(1)
    time.sleep(0.1)pbar.close()
 10%|█         | 10/100 [00:00<00:08, 10.03it/s]

tqdm常见参数

我们看看tqdm类的各个参数及其作用。

class tqdm(object):
  def __init__(self, iterable=None, desc=None, total=None):
  • iterable: 待修饰的可迭代对象,上面所有的tqdm使用例子实际上都是iterable参数起作用。默认接受第一个参数

  • desc: 进度条里加入前缀

  • total: 进度条长度,比如total=100,进度条完整的要更新一百次。

import time 

pbar = tqdm(total=100)for i in range(10):
    pbar.update(1)
    time.sleep(0.1)pbar.close()
 10%|█         | 10/100 [00:00<00:09,  9.92it/s]
import time 

pbar = tqdm(total=100, desc='大邓')for i in range(10):
    pbar.update(1)
    time.sleep(0.1)pbar.close()
大邓:  10%|█         | 10/100 [00:00<00:09,  9.93it/s]

猜你喜欢

转载自blog.csdn.net/qq_41841569/article/details/86535843