百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Python控制台进度条神器tqdm(python 控制台进度条)

toyiye 2024-07-08 23:15 13 浏览 0 评论

前言

有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事。

tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况、结合pandas,等进度展示。

大家先看看tqdm的进度条效果

安装

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

想要安装tqdm也是非常简单的,通过pipconda就可以安装,而且不需要安装其他的依赖库

pip安装

pip install tqdm

conda安装

conda install -c conda-forge tqdm

迭代对象处理

对于可以迭代的对象都可以使用下面这种方式,来实现可视化进度,非常方便

from tqdm import tqdm
import time
for i in tqdm(range(100)):
 time.sleep(0.1)
 pass

在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)代码如下

from tqdm import tqdm,trange
import time
for i in trange(100):
 time.sleep(0.1)
 pass

观察处理的数据

通过tqdm提供的set_description方法可以实时查看每次处理的数据

from tqdm import tqdm
import time
pbar = tqdm(["a","b","c","d"])
for c in pbar:
 time.sleep(1)
 pbar.set_description("Processing %s"%c)

手动设置处理的进度

通过update方法可以控制每次进度条更新的进度

from tqdm import tqdm
import time
#total参数设置进度条的总长度
with tqdm(total=100) as pbar:
 for i in range(100):
 time.sleep(0.05)
 #每次更新进度条的长度
 pbar.update(1)

除了使用with之外,还可以使用另外一种方法实现上面的效果

from tqdm import tqdm
import time
#total参数设置进度条的总长度
pbar = tqdm(total=100)
for i in range(100):
 time.sleep(0.05)
 #每次更新进度条的长度
 pbar.update(1)
#关闭占用的资源
pbar.close()

linux命令展示进度条

不使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
857365
real 0m3.458s
user 0m0.274s
sys 0m3.325s

使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365
real 0m3.585s
user 0m0.862s
sys 0m3.358s

指定tqdm的参数控制进度条

$ find . -name '*.py' -type f -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]

自定义进度条显示信息

通过set_descriptionset_postfix方法设置进度条显示信息

from tqdm import trange
from random import random,randint
import time
with trange(100) as t:
 for i in t:
 #设置进度条左边显示的信息
 t.set_description("GEN %i"%i)
 #设置进度条右边显示的信息
 t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])
 time.sleep(0.1)
from tqdm import tqdm
import time
with tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",
 postfix=["Batch",dict(value=0)]) as t:
 for i in range(10):
 time.sleep(0.05)
 t.postfix[1]["value"] = i / 2
 t.update()

多层循环进度条

通过tqdm也可以很简单的实现嵌套循环进度条的展示

from tqdm import tqdm
import time
for i in tqdm(range(20), ascii=True,desc="1st loop"):
 for j in tqdm(range(10), ascii=True,desc="2nd loop"):
 time.sleep(0.01)

在pycharm中执行以上代码的时候,会出现进度条位置错乱,目前官方并没有给出好的解决方案,这是由于pycharm不支持某些字符导致的,不过可以将上面的代码保存为脚本然后在命令行中执行,效果如下

多进程进度条

在使用多进程处理任务的时候,通过tqdm可以实时查看每一个进程任务的处理情况

from time import sleep
from tqdm import trange, tqdm
from multiprocessing import Pool, freeze_support, RLock
L = list(range(9))
def progresser(n):
 interval = 0.001 / (n + 2)
 total = 5000
 text = "#{}, est. {:<04.2}s".format(n, interval * total)
 for i in trange(total, desc=text, position=n,ascii=True):
 sleep(interval)
if __name__ == '__main__':
 freeze_support() # for Windows support
 p = Pool(len(L),
 # again, for Windows support
 initializer=tqdm.set_lock, initargs=(RLock(),))
 p.map(progresser, L)
 print("\n" * (len(L) - 2))

pandas中使用tqdm

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

递归使用进度条

下面的代码是实现递归遍历文件夹

from tqdm import tqdm
import os.path
def find_files_recursively(path, show_progress=True):
 files = []
 # total=1 assumes `path` is a file
 t = tqdm(total=1, unit="file", disable=not show_progress)
 if not os.path.exists(path):
 raise IOError("Cannot find:" + path)
 def append_found_file(f):
 files.append(f)
 t.update()
 def list_found_dir(path):
 """returns os.listdir(path) assuming os.path.isdir(path)"""
 try:
 listing = os.listdir(path)
 except:
 return []
 # subtract 1 since a "file" we found was actually this directory
 t.total += len(listing) - 1
 # fancy way to give info without forcing a refresh
 t.set_postfix(dir=path[-10:], refresh=False)
 t.update(0) # may trigger a refresh
 return listing
 def recursively_search(path):
 if os.path.isdir(path):
 for f in list_found_dir(path):
 recursively_search(os.path.join(path, f))
 else:
 append_found_file(path)
 recursively_search(path)
 t.set_postfix(dir=path)
 t.close()
 return files
find_files_recursively("E:/")

注意

在使用tqdm显示进度条的时候,如果代码中存在print可能会导致输出多行进度条,此时可以将print语句改为tqdm.write,代码如下

for i in tqdm(range(10),ascii=True):
 tqdm.write("come on")
 time.sleep(0.1)

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码