Python控制台进度图神器(python控制台在哪)
off999 2024-09-14 07:16 74 浏览 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)
相关推荐
- 在NAS实现直链访问_如何访问nas存储数据
-
平常在使用IPTV或者TVBOX时,经常自己会自定义一些源。如何直链的方式引用这些自定义的源呢?本人基于armbian和CasaOS来创作。使用标准的Web服务器(如Nginx或Apache...
- PHP开发者必备的Linux权限核心指南
-
本文旨在帮助PHP开发者彻底理解并解决在Linux服务器上部署应用时遇到的权限问题(如Permissiondenied)。核心在于理解“哪个用户(进程)在访问哪个文件(目录)”。一、核心...
- 【Linux高手必修课】吃透sed命令!文本手术刀让你秒变运维大神!
-
为什么说sed是Linux运维的"核武器"?想象你有10万个配置文件需要批量修改?传统方式要写10万行脚本?sed一个命令就能搞定!这正是运维工程师的"暴力美学"时...
- 「实战」docker-compose 编排 多个docker 组成一个集群并做负载
-
本文目标docker-compose,对springboot应用进行一个集群(2个docker,多个类似,只要在docker-compose.yml再加boot应用的服务即可)发布的过程架构...
- 企业安全访问网关:ZeroNews反向代理
-
“我们需要让外包团队访问测试环境,但不想让他们看到我们的财务系统。”“审计要求我们必须记录所有第三方对内部系统的访问,现在的VPN日志一团糟。”“每次有新员工入职或合作伙伴接入,IT部门都要花半天时间...
- 反向代理以及其使用场景_反向代理实现过程
-
一、反向代理概念反向代理(ReverseProxy)是一种服务器配置,它将客户端的请求转发给内部的另一台或多台服务器处理,然后将响应返回给客户端。与正向代理(ForwardProxy)不同,正向代...
- Nginx反向代理有多牛?一篇文章带你彻底搞懂!
-
你以为Nginx只是个简单的Web服务器?那可就大错特错了!这个看似普通的开源软件,实际上隐藏着惊人的能力。今天我们就来揭开它最强大的功能之一——反向代理的神秘面纱。反向代理到底是什么鬼?想象一下你...
- Nginx反向代理最全详解(原理+应用+案例)
-
Nginx反向代理在大型网站有非常广泛的使用,下面我就重点来详解Nginx反向代理@mikechen文章来源:mikechen.cc正向代理要理解清楚反向代理,首先:你需要搞懂什么是正向代理。正向代理...
- centos 生产环境安装 nginx,包含各种模块http3
-
企业级生产环境Nginx全模块构建的大部分功能,包括HTTP/2、HTTP/3、流媒体、SSL、缓存清理、负载均衡、DAV扩展、替换过滤、静态压缩等。下面我给出一个完整的生产环境安装流程(C...
- Nginx的负载均衡方式有哪些?_nginx负载均衡机制
-
1.轮询(默认)2.加权轮询3.ip_hash4.least_conn5.fair(最小响应时间)--第三方6.url_hash--第三方...
- Nginx百万并发优化:如何提升100倍性能!
-
关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。Nginx是大型架构的核心,下面我重点详解Nginx百万并发优化@mikechen文章来源:mikechen....
- 在 Red Hat Linux 上搭建高可用 Nginx + Keepalived 负载均衡集群
-
一、前言在现代生产环境中,负载均衡是确保系统高可用性和可扩展性的核心技术。Nginx作为轻量级高性能Web服务器,与Keepalived结合,可轻松实现高可用负载均衡集群(HA+LB...
- 云原生(十五) | Kubernetes 篇之深入了解 Pod
-
深入了解Pod一、什么是PodPod是一组(一个或多个)容器(docker容器)的集合(就像在豌豆荚中);这些容器共享存储、网络、以及怎样运行这些容器的声明。我们一般不直接创建Pod,而是...
- 云原生(十七) | Kubernetes 篇之深入了解 Deployment
-
深入了解Deployment一、什么是Deployment一个Deployment为Pods和ReplicaSets提供声明式的更新能力。你负责描述Deployment中的目标状...
- 深入理解令牌桶算法:实现分布式系统高效限流的秘籍
-
在高并发系统中,“限流”是保障服务稳定的核心手段——当请求量超过系统承载能力时,合理的限流策略能避免服务过载崩溃。令牌桶算法(TokenBucket)作为最经典的限流算法之一,既能控制请求的平...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)