Python进度条tqdm详细介绍

article/2025/9/20 10:14:22
前言

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

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

大家先看看tqdm的进度条效果
在这里插入图片描述

安装

github地址:https://github.com/tqdm/tqdm
想要安装tqdm也是非常简单的,通过pip或conda就可以安装,而且不需要安装其他的依赖库

pip安装
pip install tqdm
conda安装
conda install -c conda-forge tqdm
迭代对象处理

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

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

在这里插入图片描述
在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)代码如下

from tqdm import tqdm,trange
import timefor i in trange(100):time.sleep(0.1)pass
观察处理的数据

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

from tqdm import tqdm
import timepbar = 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
857365real    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]
857365real    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 timewith 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 timewith 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 / 2t.update()

在这里插入图片描述

多层循环进度条

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

from tqdm import tqdm
import timefor 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, RLockL = list(range(9))def progresser(n):interval = 0.001 / (n + 2)total = 5000text = "#{}, 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 supportp = Pool(len(L),# again, for Windows supportinitializer=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 tqdmdf = 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.pathdef find_files_recursively(path, show_progress=True):files = []# total=1 assumes `path` is a filet = 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 directoryt.total += len(listing) - 1# fancy way to give info without forcing a refresht.set_postfix(dir=path[-10:], refresh=False)t.update(0)  # may trigger a refreshreturn listingdef 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 filesfind_files_recursively("E:/")

在这里插入图片描述

注意

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

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

http://chatgpt.dhexx.cn/article/gXIFFiIY.shtml

相关文章

【python第三方库】tqdm简介

转载自&#xff1a; https://blog.csdn.net/wxd1233/article/details/118371404 仅作学习记录&#xff0c;侵删~ 文章目录 介绍安装使用方法1.传入可迭代对象使用trange 2.为进度条设置描述3.手动控制进度4.tqdm的write方法5.手动设置处理的进度6.自定义进度条显示信息 在深度学…

【tqdm】进度条工具

tqdm 是一种呈现循环进度的工具包&#xff0c;本文讲讲述他的常用用法。 Example 1 假设FL框架中一共有10个用户&#xff0c;每次随机抽取5个用户进行更新&#xff0c;一共训练6个epochs&#xff0c;结合tqdm显示训练进程的代码框架如下&#xff1a; for epoch in range(6):…

tqdm模块

首先给大家看看tqdm源码中的一段注释&#xff1a; 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. 如果翻译过来&#xff1a; tqdm是…

python库tqdm是什么以及怎么用tqdm、trange和tqdm.notebook

1.是什么&#xff1f; 答案&#xff1a;用来显示进度条以及展示每一轮&#xff08;iteration)所耗费的时间。好抽象&#xff0c;我们重点看怎么用&#xff0c;从而明白是什么。 2.怎么用&#xff1f; 自行安装&#xff0c;如果是anaconda的话这个是默认已经安装了的。从而导入…

Py之tqdm:tqdm库的简介、安装、使用方法详细攻略

Py之tqdm&#xff1a;tqdm库的简介、安装、使用方法详细攻略 目录 tqdm库的简介 tqdm库的安装 tqdm库的使用方法 tqdm库的简介 显示循环的进度条的库。taqadum, تقدّم&#xff09;在阿拉伯语中的意思是进展。tqdm可以在长循环中添加一个进度提示信息&#xff0c;用户只…

tqdm安装

环境&#xff1a;win10 Python3.6 首先&#xff0c;直接使用pip安装&#xff1a;pip install tqdm &#xff0c;成功安装&#xff0c;但是导入不了tqdm进行使用。 import tqdm from tqdm import tqdm Traceback (most recent call last):File "D:\Anaconda3\lib\site-…

【PyTorch总结】tqdm的使用

文章目录 介绍安装使用方法1.传入可迭代对象使用trange2.为进度条设置描述3.手动控制进度4.tqdm的write方法5.手动设置处理的进度6.自定义进度条显示信息 在深度学习中如何使用 介绍 Tqdm 是 Python 进度条库&#xff0c;可以在 Python 长循环中添加一个进度提示信息。用户只需…

Python的Tqdm模块——进度条配置

tqdm官网地址&#xff1a;https://pypi.org/project/tqdm/ Github地址&#xff1a;https://github.com/tqdm/tqdm 简介 Tqdm 是一个快速&#xff0c;可扩展的Python进度条&#xff0c;可以在 Python 长循环中添加一个进度提示信息&#xff0c;用户只需要封装任意的迭代器 tqd…

tqdm 简介及正确的打开方式

tqdm 简介及正确的打开方式 查遍了网上资料&#xff0c;发现绝大中文的讲解全都是一手带过&#xff0c;还称详细&#xff0c;真是醉了&#xff0c;于是有该文&#xff0c;也算给自己做个笔记 1. 什么是tqdm&#xff1f; tqdm是一个快速的&#xff0c;易扩展的进度条提示模块&a…

tqdm库

tqdm库 文章目录 tqdm库如何安装如何使用1.基于迭代的进度条2.手动设置进度条 如何在Pandas中使用进度条如何在keras中使用进度条如何使用Notebook优化的进度条和层级进度条如何为文件存储设置进度条 简要介绍&#xff1a; tqdm是一个进度条可视化库&#xff0c;可以帮助我们监…

tqdm的使用和例子

1. tqdm的介绍 有时候在使用Python处理比较耗时操作的时候&#xff0c;为了便于观察处理进度&#xff0c;这时候就需要通过进度条将处理情况进行可视化展示&#xff0c;以便我们能够及时了解情况。 tqdm就能非常完美的支持和解决这些问题&#xff0c;可以实时输出处理进度而且…

一个被忽视的Python神器 - Tqdm

1. 什么是Tqdm 在日常工作和学习中&#xff0c;经常需要观察当前任务的执行进度&#xff0c;尤其是一个执行时间很长的任务&#xff0c;如果能够有进度条实时的显示当前的任务进度&#xff0c;那么将非常方便。 Tqdm 是一个快速&#xff0c;可扩展的Python进度条&#xff0c;…

tqdm 详解

文章目录 1. 简介2. 使用方法3. 实例 - 手写数字识别 1. 简介 tqdm是 Python 进度条库&#xff0c;可以在 Python长循环中添加一个进度提示信息。用户只需要封装任意的迭代器&#xff0c;是一个快速、扩展性强的进度条工具库。 2. 使用方法 传入可迭代对象 import time from…

idea方法注释的快捷键设置idea自定义注释设置

作者: yibox_qcby目录 效果展示配置步骤第一步第二步第三步第四步第五步第六步 完成 效果展示 配置步骤 第一步 第二步 第三步 第四步 注意第一行不是/** *** ClassName $className$* Description : 功能说明* $params$* Return : $return$* Author : 作者* Date : $DATE$ $…

idea中使用注释快捷键的问题及解决办法

问题描述 在idea中&#xff0c;使用注释快捷键会产生在注释前面会有缩进&#xff0c;这种缩进对于有着强迫症的我简直受不了 在按照网上其他的教程进行相关设置之后还是出现这样的问题 解决方法 我在使用中偶然发现idea注释的快捷键除了行注释&#xff08;Ctrl/&#xff…

idea文档注释的快捷键带参数

注意&#xff1a;为了大家能逐步了解 对这个小功能有个熟悉的过程 &#xff08;其实是作者比较懒 不想从头到尾重新截图 ) 发现问题会在文章未陆续更新 建议把整篇文章都看完 如果懒得看过程 看完开头后 文章最后代码直接复制进去就好了 输入 /** 按回车&#xff0c;当然这肯定…

IDEA设置类和方法的注释快捷键

一、设置类的注释快捷键 1.打开file->setting->Editor->Filr and Code Templates->Includes->File Header&#xff0c;如下图所示&#xff1a; 2.注释模板参考&#xff1a; /**1. description: 2. author: ManolinCoder3. time: ${DATE} */ 3.创建类时候自动…

修改idea快捷键注释样式

打开设置 找到Editor -> Code Style -> Java 以修改xxx.java文件注释样式&#xff0c;点击其它位置&#xff0c;修改其它语言注释样式 找到Code Generation 取消Line comment at first column和Block comment at first column&#xff0c;勾上Add a space at line commen…

idea 方法注释的快捷键设置

1.打开设置setting->Editor->Live Templates 2.然后点击号&#xff0c;选择第二个&#xff0c;设置一个自定义的组&#xff0c;输入名字&#xff0c;这里我叫mytemp 3.选定刚才创建的组&#xff0c;再次点击号&#xff0c;创建一个模板&#xff0c;重点&#xff0c;写模板…

IDEA的三种注释快捷键

一.行注释 1.1快捷键&#xff1a;Ctrl/ 1.2效果演示&#xff1a; 二.块注释 2.1快捷键&#xff1a;CtrlShift/ 2.2效果演示&#xff1a; 三.方法说明注释 3.1快捷键&#xff1a;输入/** ,点击“Enter”&#xff0c;自动根据参数和返回值生成注释模板