百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python控制台进度图神器(python控制台在哪)

off999 2024-09-14 07:16 27 浏览 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)

相关推荐

Python 数据分析——利用Pandas进行分组统计

话说天下大势,分久必合,合久必分。数据分析也是如此,我们经常要对数据进行分组与聚合,以对不同组的数据进行深入解读。本章将介绍如何利用Pandas中的GroupBy操作函数来完成数据的分组、聚合以及统计...

python数据分析:介绍pandas库的数据类型Series和DataFrame

安装pandaspipinstallpandas-ihttps://mirrors.aliyun.com/pypi/simple/使用pandas直接导入即可importpandasas...

使用DataFrame计算两列的总和和最大值_[python]

【如果对您有用,请关注并转发,谢谢~~】最近在处理气象类相关数据的空间计算,在做综合性计算的时候,DataFrame针对每列的统计求和、最大值等较为方便,对某行的两列或多列数据进行求和与最大值等的简便...

8-Python内置函数

Python提供了丰富的内置函数,这些函数可以直接使用而无需导入任何模块。以下是一些常用的内置函数及其示例:1-print()1-1-说明输出指定的信息到控制台。1-2-例子2-len()2-1-说...

Python中函数式编程函数: reduce()函数

Python中的reduce()函数是一个强大的工具,它通过连续地将指定的函数应用于序列(如列表)来对序列(如列表)执行累积操作。它是functools模块的一部分,这意味着您需要在使用它之...

万万没想到,除了香农计划,Python3.11竟还有这么多性能提升

众所周知,Python3.11版本带来了较大的性能提升,但是,它具体在哪些方面上得到了优化呢?除了著名的“香农计划”外,它还包含哪些与性能相关的优化呢?本文将带你一探究竟!作者:BeshrKay...

最全python3.11版12类75个内置函数大全

获取全部内置函数:importbuiltins#导入模块yc=[]#异常属性nc=[]#不可调用fn=[]#内置函数defll(ty=builtins):...

软件测试笔试题

测试工程师岗位,3-5年,10-14k1.我司有一款产品,类似TeamViewer,向日葵,mstsc,QQ远程控制产品,一个PC客户端产品,请设想一下测试要点。并写出2.写出常用的SQL语句8条,l...

备战各大互联网巨头公司招聘会,最全Python面试大全,共300题

前言众所周知,越是顶尖的互联网公司在面试这一part的要求就越高,需要你有很好的技术功底、项目经验、一份漂亮的简历,当然还有避免不了的笔试过关。对于Python的工程师来说,全面掌握好有关Python...

经典 SQL 数据库笔试题及答案整理

马上又是金三银四啦,有蛮多小伙伴在跳槽找工作,但对于年限稍短的软件测试工程师,难免会需要进行笔试,而在笔试中,基本都会碰到一道关于数据库的大题,今天这篇文章呢,就收录了下最近学员反馈上来的一些数据库笔...

用Python开发日常小软件,让生活与工作更高效!附实例代码

引言:Python如何让生活更轻松?在数字化时代,编程早已不是程序员的专属技能。Python凭借其简洁易学的特点,成为普通人提升效率、解决日常问题的得力工具。无论是自动化重复任务、处理数据,还是开发个...

太牛了!102个Python实战项目被我扒到了!建议收藏!

挖到宝了!整整102个Python实战项目合集,从基础语法到高阶应用全覆盖,附完整源码+数据集,手把手带你从代码小白变身实战大神!这波羊毛不薅真的亏到哭!超全项目库,学练一站式搞定这份资...

Python中的并发编程

1.Python对并发编程的支持多线程:threading,利用CPU和IO可以同时执行的原理,让CPU不会干巴巴等待IO完成。多进程:multiprocessing,利用多核CPU...

Python 也有内存泄漏?

1.背景前段时间接手了一个边缘视觉识别的项目,大功能已经开发的差不多了,主要是需要是优化一些性能问题。其中比较突出的内存泄漏的问题,而且不止一处,有些比较有代表性,可以总结一下。为了更好地可视化内存...

python爬虫之多线程threading、多进程、协程aiohttp批量下载图片

一、单线程常规下载常规单线程执行脚本爬取壁纸图片,只爬取一页的图片。importdatetimeimportreimportrequestsfrombs4importBeautifu...

取消回复欢迎 发表评论: