前言

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

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

大家先看看tqdm的进度条效果

安装

想要安装tqdm也是非常简单的,通过pip或conda就可以安装,而且不需要安装其他的依赖库

pip安装

1pip install tqdm

conda安装

1conda install-c conda-forge tqdm

迭代对象处理

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

1

2

3

4

5

6from tqdmimport tqdm

import time

for iin tqdm(range(100)):

time.sleep(0.1)

pass

在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)代码如下

1

2

3

4

5

6from tqdmimport tqdm,trange

import time

for iin trange(100):

time.sleep(0.1)

pass

观察处理的数据

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

1

2

3

4

5

6

7from tqdmimport tqdm

import time

pbar= tqdm(["a","b","c","d"])

for cin pbar:

time.sleep(1)

pbar.set_description("Processing %s"%c)

手动设置处理的进度

通过update方法可以控制每次进度条更新的进度

1

2

3

4

5

6

7

8

9from tqdmimport tqdm

import time

#total参数设置进度条的总长度

with tqdm(total=100) as pbar:

for iin range(100):

time.sleep(0.05)

#每次更新进度条的长度

pbar.update(1)

除了使用with之外,还可以使用另外一种方法实现上面的效果

1

2

3

4

5

6

7

8

9

10

11from tqdmimport tqdm

import time

#total参数设置进度条的总长度

pbar= tqdm(total=100)

for iin range(100):

time.sleep(0.05)

#每次更新进度条的长度

pbar.update(1)

#关闭占用的资源

pbar.close()

linux命令展示进度条

不使用tqdm

1

2

3

4

5

6$time find . -name'*.py' -type f -exec cat \{} \; |wc -l

857365

real  0m3.458s

user  0m0.274s

sys   0m3.325s

使用tqdm

1

2

3

4

5

6

7$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的参数控制进度条

1

2

3$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]

1

2

3$ 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方法设置进度条显示信息

1

2

3

4

5

6

7

8

9

10

11from tqdmimport trange

from randomimport random,randint

import time

with trange(100) as t:

for iin 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)

1

2

3

4

5

6

7

8

9from tqdmimport tqdm

import time

with tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",

postfix=["Batch",dict(value=0)]) as t:

for iin range(10):

time.sleep(0.05)

t.postfix[1]["value"]= i/ 2

t.update()

多层循环进度条

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

1

2

3

4

5

6from tqdmimport tqdm

import time

for iin tqdm(range(20), ascii=True,desc="1st loop"):

for jin tqdm(range(10), ascii=True,desc="2nd loop"):

time.sleep(0.01)

在pycharm中执行以上代码的时候,会出现进度条位置错乱,目前官方并没有给出好的解决方案,这是由于pycharm不支持某些字符导致的,不过可以将上面的代码保存为脚本然后在命令行中执行,效果如下

多进程进度条

在使用多进程处理任务的时候,通过tqdm可以实时查看每一个进程任务的处理情况

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20from timeimport sleep

from tqdmimport trange, tqdm

from multiprocessingimport 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 iin 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

1

2

3

4

5

6

7

8

9import pandas as pd

import numpy as np

from tqdmimport tqdm

df= pd.DataFrame(np.random.randint(0,100, (100000,6)))

tqdm.pandas(desc="my bar!")

df.progress_apply(lambda x: x**2)

递归使用进度条

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40from tqdmimport 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 fin 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,代码如下

1

2

3for iin tqdm(range(10),ascii=True):

tqdm.write("come on")

time.sleep(0.1)

tqdm 显示其他_详细介绍Python进度条tqdm的使用相关推荐

  1. python3 进度条_详细介绍Python进度条tqdm的使用

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

  2. Python 进度条 tqdm

    Python 进度条 tqdm from tqdm import tqdm import time#total参数设置进度条的总长度 pbar = tqdm(total=100) for i in r ...

  3. python位运算符_详细介绍Python语言中的按位运算符

    按位运算符是把数字看作二进制来进行计算的.Python中的按位运算法则如下: 按位与 ( bitwise and of x and y ) & 举例: 5&3 = 1 解释: 101 ...

  4. python or的用法_详细介绍Python中and和or实际用法

    and 和 or 的特殊性质 在Python 中,and 和 or 执行布尔逻辑演算,但是它们并不返回布尔值:而是,返回它们实际进行比较的值之一.下面来看一下实例.>>> 'a' a ...

  5. python进度条tqdm

    文章目录 1. 简介 2. 安装 3. 使用方法 3.1 自动控制 3.2 手动控制的形式 4. 总结 4.1 基于迭代对象运行: tqdm(iterator) 4.2 手动进行更新 4.3 tqdm ...

  6. python语言中运算符号_详细介绍Python语言中的按位运算符

    <从问题到程序:用Python学编程和计算>--2.11 补充材料 本节书摘来自华章计算机<从问题到程序:用Python学编程和计算>一书中的第2章,第2.11节,作者:裘宗燕 ...

  7. python 偏函数_详细介绍Python中的偏函数

    机器学习实战之Logistic回归 本文来自云栖社区官方钉群"Python技术进阶",了解相关信息可以关注"Python技术进阶". 本系列教程特点: 基于&l ...

  8. python链表详细教程_详细介绍python数据结构之链表

    这篇文章主要为大家详细介绍了python数据结构之链表的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 数据结构是计算机科学必须掌握的一门学问,之前很多的教材都是用C语言实现链表,因为c有 ...

  9. python实现简单进度条_简单实现python进度条脚本

    最近需要用Python写一个小脚本,用到了一些小知识,赶紧抽空记录一下.不深但是常用. 两个进度条示例,拷贝就能运行: # coding=utf-8 import sys import time # ...

最新文章

  1. spyder一打开就卡了_欧姆龙plc 用 SD 卡上传/下载程序
  2. SIEM已死?标题党!
  3. 换光纤猫 ZXA10 F420
  4. 算法系列15天速成——第十三天 树操作【下】
  5. 现代控制会用到python嘛_Python 流程控制
  6. elementui 弹窗 显示详细信息_ElementUI中el-table双击单元格事件并获取指定列的值和弹窗显示详细信息...
  7. C++_类和对象_对象特性_拷贝构造函数调用时机---C++语言工作笔记042
  8. SDP 软件定义边界
  9. FlexboxLayout——Android弹性布局
  10. Android自定义View—刮刮卡效果
  11. 深度好文:这才是实际工作中的竞品分析
  12. 识别到硬盘 计算机不显示盘符,移动硬盘不显示盘符怎么办
  13. Window7使用虚拟桌面
  14. KepServer如何和欧姆龙NJ系列通讯并进行字符串读取
  15. 【子桓说】某大学毕业生:我很嫉妒月入10万的网红
  16. [开源]CMSIS-DAP高速下载器
  17. day14_雷神_前端02
  18. 高通android逆向分析,浅谈Android高通(Qualcomm)和联发科(MTK)平台
  19. php怎么把csv转换成excel_php如何把excel转化为csv
  20. 文本分类中样本的筛选(基于VSM模型)

热门文章

  1. 易中天品三国 - 雨热闲坛
  2. 速达数据库服务器密码修改,如何创建SQL数据库登录用户及密码? 找昆明速达软件...
  3. [ php ] php中io操作!
  4. JAVA的进一步学习
  5. 转载10gocp翻译
  6. matlab——逻辑运算符——与、或、非
  7. 数字藏品与NFT到底有何区别?
  8. seata xid不传递
  9. nginx-rtmp(直播点播)配置
  10. 中国井冈山干部学院莅临红谷滩区·高通中国·影创联合创新中心考察调研