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

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

off999 2024-09-14 07:16 36 浏览 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列表(List)必会的13个核心技巧(附实用方法)

列表(List)是Python入门的关键步骤,因为它是编程中最常用的数据结构之一。以下是高效掌握列表的核心技巧和实用方法:一、理解列表的本质可变有序集合:可随时修改内容,保持元素顺序混合类型:一个列表...

Python列表(List)一文全掌握:核心知识点+20实战练习题

Python列表(List)知识点教程一、列表的定义与特性定义:列表是可变的有序集合,用方括号[]定义,元素用逗号分隔。list1=[1,"apple",3.14]lis...

python编程中列表常见的9大问题,你知道吗?

Python列表常见错误及解决方案列表(list)是Python中最常用的数据结构之一,但在使用过程中经常会遇到各种问题。以下是Python列表使用中的常见错误及其解决方法:一、索引越界错误1.访问...

python之列表操作(python列表操作函数大全)

常用函数函数名功能说明append将一个元素添加到列表中names=['tom']用法:names.append('tommy')注意事项:被添加的元素只会被添加到...

7 种在 Python 中反转列表的智能方法

1.使用reverse()方法(原地)my_list=[10,12,6,34,23]my_list.reverse()print(my_list)#output:[23,34,6,12,...

Python教程-列表复制(python中列表copy的用法)

作为软件开发者,我们总是努力编写干净、简洁、高效的代码。Python列表是一种多功能的数据结构,它允许你存储一个项目的集合。在Python中,列表是可变的,这意味着你可以在创建一个列表后改变它的...

「Python程序设计」基本数据类型:列表(数组)

列表是python程序设计中的一个基本的,也是重要的数据结构。我们可以把列表数据结构,理解为其它编程语言中的数组。定义和创建列表列表中的数据元素的索引,和数组基本一致,第一个元素的索引,或者是下标为0...

Python中获取列表最后一个元素的方法

技术背景在Python编程中,经常会遇到需要获取列表最后一个元素的场景。Python提供了多种方法来实现这一需求,不同的方法适用于不同的场景。实现步骤1.使用负索引-1这是最简单和最Pythoni...

Python学不会来打我(11)列表list详解:用法、场景与类型转换

在Python编程中,列表(list)是最常用且功能最强大的数据结构之一。它是一个有序、可变、支持重复元素的集合,可以存储任意类型的对象,包括整数、字符串、布尔值、甚至其他列表。本文将从基础语法开始...

零起点Python机器学习快速入门-4-4-列表操作

Python列表的基本操作展开。首先,定义了两个列表zlst和vlst并将它们的内容打印出来。接着,使用切片操作从这两个列表中提取部分元素,分别得到s2、s3和s4三个新的列表,并打...

python入门 到脱坑 基本数据类型—列表

以下是Python列表(List)的入门详解,包含基础操作、常用方法和实用技巧,适合初学者系统掌握:一、列表基础1.定义列表#空列表empty_list=[]#包含不同类型元素的列表...

Python 列表(List)完全指南:数据操作的利器

在Python中,列表(list)是一种可变序列(mutablesequence),它允许我们存储和操作一组有序数据(ordereddata)。本教程将从基础定义(basicdefiniti...

如何快速掌握 Python中列表的使用

学习python知识,好掌握Python列表的使用。从概念上来讲,Python中的列表list是一种有序、可变的容器,可以存储任意类型的数据(包括其他列表)。以下是列表的常用的操作和知识:1....

Python中的列表详解及示例(python中列表的用法)

艾瑞巴蒂干货来了,数据列表,骚话没有直接来吧列表(List)是Python中最基本、最常用的数据结构之一,它是一个有序的可变集合,可以包含任意类型的元素。列表的基本特性有序集合:元素按插入顺序存储可变...

python数据类型之列表、字典、元组、集合及操作

Python数据类型进阶:列表、字典与集合在Python中,数据类型是编程的基础,熟练掌握常用数据结构是成为高级开发者的关键。上一篇文章我们学习到了Python的数据类型:字符串(string)、数...

取消回复欢迎 发表评论: