[917]python的tqdm模块——进度条配置

tqdm官网地址:https://pypi.org/project/tqdm/

Github地址:https://github.com/tqdm/tqdm

简介

Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。

总之,它是用来显示进度条的,很漂亮,使用很直观(在循环体里边加个tqdm),而且基本不影响原程序效率。名副其实的“太强太美”了!这样在写运行时间很长的程序时,是该多么舒服啊!

给一张GIF图看一下实际效果

安装

pip install tqdm

tqdm模块参数说明

class tqdm(object):
  """
  Decorate an iterable object, returning an iterator which acts exactly
  like the original iterable, but prints a dynamically updating
  progressbar every time a value is requested.
  """

  def __init__(self, iterable=None, desc=None, total=None, leave=False,
               file=sys.stderr, ncols=None, mininterval=0.1,
               maxinterval=10.0, miniters=None, ascii=None,
               disable=False, unit='it', unit_scale=False,
               dynamic_ncols=False, smoothing=0.3, nested=False,
               bar_format=None, initial=0, gui=False):
  • iterable: 可迭代的对象, 在手动更新时不需要进行设置
  • desc: 字符串, 左边进度条描述文字
  • total: 总的项目数
  • leave: bool值, 迭代完成后是否保留进度条
  • file: 输出指向位置, 默认是终端, 一般不需要设置
  • ncols: 调整进度条宽度, 默认是根据环境自动调节长度, 如果设置为0, 就没有进度条, 只有输出的信息
  • unit: 描述处理项目的文字, 默认是’it’, 例如: 100 it/s, 处理照片的话设置为’img’ ,则为 100 img/s
  • unit_scale: 自动根据国际标准进行项目处理速度单位的换算, 例如 100000 it/s >> 100k it/s

下面是实例展示

import time
from tqdm import tqdm

# 发呆0.5s
def action():
    time.sleep(0.5)
with tqdm(total=100000, desc='Example', leave=True, ncols=100, unit='B', unit_scale=True) as pbar:
    for i in range(10):
        # 发呆0.5秒
        action()
        # 更新发呆进度
        pbar.update(10000)
Example: 100%|███████████████████████████████████████████████████| 100k/100k [00:05<00:00, 19.6kB/s]

使用

示例一
简单的demo:

# !/user/bin/env python
# -*- coding:utf-8 -*-
 
import time
from tqdm import tqdm,trange
#from tqdm._tqdm import trange
 
for i in tqdm(range(100)):
    time.sleep(0.01)

输出结果如下:

100%|██████████| 100/100 [00:01<00:00, 93.09it/s]

关于tqdm对于range的封装

import time
from tqdm import tqdm
from tqdm._tqdm import trange
 
for j in trange(100):
    time.sleep(0.1)

输出结果如下(同上)

100%|██████████| 100/100 [00:01<00:00, 93.09it/s]

带参数

from tqdm import tqdm
import time
d = {'loss':0.2,'learn':0.8}
#desc设置名称,ncols设置进度条长度.postfix以字典形式传入详细信息
for i in tqdm(range(50),desc='进行中',ncols=10,postfix=d): 
    time.sleep(0.1)

输出结果如下

进行中: 100%|█| 50/50 [00:05<00:00,  9.93it/s, learn=0.8, loss=0.2]

示例二:
对于任意list的使用

alist = list('letters')
bar = tqdm(alist)
for letter in bar:
    bar.set_description(f"Now get {letter}")

输出结果如下:

Now get s: 100%|██████████| 7/7 [00:00<00:00, 7040.80it/s]

传入任意list

pbar = tqdm(["a", "b", "c", "d"])
for char in pbar:
    pbar.set_description("Processing %s" % char)

输出结果如下:

Processing d: 100%|██████████| 4/4 [00:00<00:00, 4013.69it/s]

手动控制更新

with tqdm(total=200) as pbar:
    pbar.set_description('Processing:')
    # total表示总的项目, 循环的次数20*10(每次更新数目) = 200(total)
    for i in range(20):
        # 进行动作, 这里是过0.1s
        time.sleep(0.1)
        # 进行进度更新, 这里设置10个
        pbar.update(10)
Processing:: 100%|██████████| 200/200 [00:02<00:00, 91.94it/s]

# 也可以这样
pbar = tqdm(total=100)
for i in range(10):
    pbar.update(10)
pbar.close()

示例三:
结合pandas的使用

import  pandas as pd
import numpy as  np
 
df = pd.DataFrame(np.random.randint(0, 100, (10000000, 6)))
tqdm.pandas(desc="my bar!")
df.progress_apply(lambda x: x**2)

输出结果如下:

my bar!: 100%|██████████| 6/6 [00:00<00:00,  6.09it/s]

示例四
在Shell的tqdm用法

$ 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

使用的参数:

$ find . -name '*.py' -exec cat \{} \; |
    tqdm --unit loc --unit_scale --total 857366 >> /dev/null
100%|███████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]

备份一个目录:

$ 7z a -bd -r backup.7z docs/ | grep Compressing |
    tqdm --total $(find docs/ -type f | wc -l) --unit files >> backup.log
100%|███████████████████████████████▉| 8014/8014 [01:37<00:00, 82.29files/s]

参考:
https://blog.csdn.net/qq_33472765/article/details/82940843
https://blog.csdn.net/langb2014/article/details/54798823?locationnum=8&fps=1
https://blog.csdn.net/feiyang5260/article/details/100050539
https://zhuanlan.zhihu.com/p/163613814

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值