首页 > python爬虫

Python的Tqdm模块实现进度条配置

时间:2021-03-21 python爬虫 查看: 807

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

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

简介

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

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

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

安装

pip install tqdm

 使用

示例一

简单的demo:

# !/user/bin/env python
# -*- coding:utf-8 -*-


import time
from tqdm import tqdm
from tqdm._tqdm import trange

for i in tqdm(range(100)):
  time.sleep(0.01)

输出结果如下:

关于tqdm对于range的封装

import time
from tqdm import tqdm
from tqdm._tqdm import trange

for j in trange(100):
  time.sleep(0.1)

输出结果如下(同上)

示例二:

对于任意list的使用

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

输出结果如下:

传入任意list

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

手动控制更新

with tqdm(total=100) as pbar:
  for i in range(10):
    pbar.update(10)


# 也可以这样
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)

 输出结果如下:

示例四

在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/langb2014/article/details/54798823?locationnum=8&fps=1

到此这篇关于Python的Tqdm模块实现进度条配置的文章就介绍到这了,更多相关Python Tqdm进度条内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

展开全文
上一篇:python实现简单文件读写函数
下一篇:pandas map(),apply(),applymap()区别解析
输入字:
相关知识
Python爬虫基础之爬虫的分类知识总结

来给大家讲python爬虫的基础啦,首先我们从爬虫的分类开始讲起,下文有非常详细的知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下

Python爬虫基础讲解之请求

今天带大家了解一下python爬虫的基础知识,文中有非常详细的解释说明,对正在学习python爬虫的小伙伴们有很好地帮助,需要的朋友可以参考下

PyQt5爬取12306车票信息程序的实现

12306是学习爬虫的比较好的一个练手网站。本文主要实现了PyQt5爬取12306车票信息程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python爬虫之m3u8文件里提取小视频的正确姿势

本文给大家分享如何正确提取m3u8文件里的.ts视频,并合成完整的.mp4格式视频,通过图文实例代码的形式给大家介绍的非常详细,对Python提取m3u8文件小视频感兴趣的朋友一起看看吧