Python控制台进度图神器(python控制台在哪)
off999 2024-09-14 07:16 32 浏览 0 评论
前言
有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事。
tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况、结合pandas,等进度展示。
大家先看看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 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_description和set_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)
相关推荐
- 面试官:来,讲一下枚举类型在开发时中实际应用场景!
-
一.基本介绍枚举是JDK1.5新增的数据类型,使用枚举我们可以很好的描述一些特定的业务场景,比如一年中的春、夏、秋、冬,还有每周的周一到周天,还有各种颜色,以及可以用它来描述一些状态信息,比如错...
- 一日一技:11个基本Python技巧和窍门
-
1.两个数字的交换.x,y=10,20print(x,y)x,y=y,xprint(x,y)输出:102020102.Python字符串取反a="Ge...
- Python Enum 技巧,让代码更简洁、更安全、更易维护
-
如果你是一名Python开发人员,你很可能使用过enum.Enum来创建可读性和可维护性代码。今天发现一个强大的技巧,可以让Enum的境界更进一层,这个技巧不仅能提高可读性,还能以最小的代价增...
- Python元组编程指导教程(python元组的概念)
-
1.元组基础概念1.1什么是元组元组(Tuple)是Python中一种不可变的序列类型,用于存储多个有序的元素。元组与列表(list)类似,但元组一旦创建就不能修改(不可变),这使得元组在某些场景...
- 你可能不知道的实用 Python 功能(python有哪些用)
-
1.超越文件处理的内容管理器大多数开发人员都熟悉使用with语句进行文件操作:withopen('file.txt','r')asfile:co...
- Python 2至3.13新特性总结(python 3.10新特性)
-
以下是Python2到Python3.13的主要新特性总结,按版本分类整理:Python2到Python3的重大变化Python3是一个不向后兼容的版本,主要改进包括:pri...
- Python中for循环访问索引值的方法
-
技术背景在Python编程中,我们经常需要在循环中访问元素的索引值。例如,在处理列表、元组等可迭代对象时,除了要获取元素本身,还需要知道元素的位置。Python提供了多种方式来实现这一需求,下面将详细...
- Python enumerate核心应用解析:索引遍历的高效实践方案
-
喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。根据GitHub代码分析统计,使用enumerate替代range(len())写法可减少38%的索引错误概率。本文通过12个生产...
- Python入门到脱坑经典案例—列表去重
-
列表去重是Python编程中常见的操作,下面我将介绍多种实现列表去重的方法,从基础到进阶,帮助初学者全面掌握这一技能。方法一:使用集合(set)去重(最简单)pythondefremove_dupl...
- Python枚举类工程实践:常量管理的标准化解决方案
-
本文通过7个生产案例,系统解析枚举类在工程实践中的应用,覆盖状态管理、配置选项、错误代码等场景,适用于Web服务开发、自动化测试及系统集成领域。一、基础概念与语法演进1.1传统常量与枚举类对比#传...
- 让Python枚举更强大!教你玩转Enum扩展
-
为什么你需要关注Enum?在日常开发中,你是否经常遇到这样的代码?ifstatus==1:print("开始处理")elifstatus==2:pri...
- Python枚举(Enum)技巧,你值得了解
-
枚举(Enum)提供了更清晰、结构化的方式来定义常量。通过为枚举添加行为、自动分配值和存储额外数据,可以提升代码的可读性、可维护性,并与数据库结合使用时,使用字符串代替数字能简化调试和查询。Pytho...
- 78行Python代码帮你复现微信撤回消息!
-
来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。[导读]Python曾经对我说:"时日不多,赶紧用Python"。于是看...
- 登录人人都是产品经理即可获得以下权益
-
文章介绍如何利用Cursor自动开发Playwright网页自动化脚本,实现从选题、写文、生图的全流程自动化,并将其打包成API供工作流调用,提高工作效率。虽然我前面文章介绍了很多AI工作流,但它们...
- Python常用小知识-第二弹(python常用方法总结)
-
一、Python中使用JsonPath提取字典中的值JsonPath是解析Json字符串用的,如果有一个多层嵌套的复杂字典,想要根据key和下标来批量提取value,这是比较困难的,使用jsonpat...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python自定义函数 (53)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python人脸识别 (54)
- python多态 (60)
- python命令行参数 (53)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)