Python小神器:脚本执行进度条

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

简介

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

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

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

安装

pip install tqdm
   
   

使用

示例一:简单的demo


   
   
  1. # !/user/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import time
  4. from tqdm import tqdm
  5. from tqdm._tqdm import trange
  6. for i in tqdm( range( 100)):
  7. time.sleep( 0.01)

输出结果如下:

关于tqdm对于range的封装


   
   
  1. import time
  2. from tqdm import tqdm
  3. from tqdm._tqdm import trange
  4. for j in trange( 100):
  5. time.sleep( 0.1)

输出结果如下(同上)

 

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


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

输出结果如下:

传入任意list


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

手动控制更新


   
   
  1. with tqdm(total= 100) as pbar:
  2. for i in range( 10):
  3. pbar.update( 10)
  4. # 也可以这样
  5. pbar = tqdm(total= 100)
  6. for i in range( 10):
  7. pbar.update( 10)
  8. pbar.close()

 

示例三:结合pandas的使用


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

 输出结果如下:

 

示例四:在Shell的tqdm用法


   
   
  1. $ time find . -name '*.py' - exec cat \{} \; | wc -l
  2. 857365
  3. real 0m3 .458s
  4. user 0m0 .274s
  5. sys 0m3 .325s
  6. $ time find . -name '*.py' - exec cat \{} \; | tqdm | wc -l
  7. 857366it [ 00:03, 246471.31it/s]
  8. 857365
  9. real 0m3 .585s
  10. user 0m0 .862s
  11. sys 0m3 .358s

 

使用的参数:


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

备份一个目录:


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

本文参考:https://blog.csdn.net/langb2014/article/details/54798823?locationnum=8&fps=1

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值