教你用Python脚本使用进度条

简介: 教你用Python脚本使用进度条

教你用Python脚本使用进度条

安装

github地址:https://github.com/tqdm/tqdm

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

pip安装

1

pip install tqdm

conda安装

1

conda install -c conda-forge tqdm

迭代对象处理

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

1

2

3

4

5

6

fromtqdm importtqdm

importtime

 

fori intqdm(range(100)):

  time.sleep(0.1)

  pass

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

1

2

3

4

5

6

fromtqdm importtqdm,trange

importtime

 

fori intrange(100):

  time.sleep(0.1)

  pass

观察处理的数据

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

1

2

3

4

5

6

7

fromtqdm importtqdm

importtime

 

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

forc inpbar:

  time.sleep(1)

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

手动设置处理的进度

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

1

2

3

4

5

6

7

8

9

fromtqdm importtqdm

importtime

 

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

with tqdm(total=100) as pbar:

  fori inrange(100):

    time.sleep(0.05)

    #每次更新进度条的长度

    pbar.update(1)

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

1

2

3

4

5

6

7

8

9

10

11

fromtqdm importtqdm

importtime

 

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

pbar =tqdm(total=100)

fori inrange(100):

  time.sleep(0.05)

  #每次更新进度条的长度

  pbar.update(1)

#关闭占用的资源

pbar.close()

linux命令展示进度条

不使用tqdm

1

2

3

4

5

6

$ timefind. -name '*.py'-typef -execcat\{} \; | wc-l

857365

 

real  0m3.458s

user  0m0.274s

sys   0m3.325s

使用tqdm


1

2

3

4

5

6

7

$ timefind. -name '*.py'-typef -execcat\{} \; | 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'-typef -execcat\{} \; |

  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/ | grepCompressing |

  tqdm --total $(finddocs/ -typef | wc-l) --unit files >> backup.log

100%|███████████████████████████████▉| 8014/8014[01:37<00:00, 82.29files/s]

自定义进度条显示信息

通过set_descriptionset_postfix方法设置进度条显示信息

1

2

3

4

5

6

7

8

9

10

11

fromtqdm importtrange

fromrandom importrandom,randint

importtime

 

with trange(100) as t:

  fori int:

    #设置进度条左边显示的信息

    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

9

fromtqdm importtqdm

importtime

 

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

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

  fori inrange(10):

    time.sleep(0.05)

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

    t.update()

多层循环进度条

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

1

2

3

4

5

6

fromtqdm importtqdm

importtime

 

fori intqdm(range(20), ascii=True,desc="1st loop"):

  forj intqdm(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

20

fromtime importsleep

fromtqdm importtrange, tqdm

frommultiprocessing importPool, freeze_support, RLock

 

L =list(range(9))

 

defprogresser(n):

  interval =0.001/(n +2)

  total =5000

  text ="#{}, est. {:<04.2}s".format(n, interval *total)

  fori intrange(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

9

importpandas as pd

importnumpy as np

fromtqdm importtqdm

 

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

 

 

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

df.progress_apply(lambdax: 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

40

fromtqdm importtqdm

importos.path

 

deffind_files_recursively(path, show_progress=True):

  files =[]

  # total=1 assumes `path` is a file

  t =tqdm(total=1, unit="file", disable=notshow_progress)

  ifnotos.path.exists(path):

    raiseIOError("Cannot find:"+path)

 

  defappend_found_file(f):

    files.append(f)

    t.update()

 

  deflist_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

    returnlisting

 

  defrecursively_search(path):

    ifos.path.isdir(path):

      forf inlist_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()

  returnfiles

 

find_files_recursively("E:/")

注意

在使用tqdm显示进度条的时候,如果代码中存在print可能会导致输出多行进度条,此时可以将print语句改为tqdm.write,代码如下

1

2

3

fori intqdm(range(10),ascii=True):

  tqdm.write("come on")

  time.sleep(0.1)

目录
相关文章
|
16天前
|
Python
用python转移小文件到指定目录并压缩,脚本封装
这篇文章介绍了如何使用Python脚本将大量小文件转移到指定目录,并在达到大约250MB时进行压缩。
31 2
|
21天前
|
运维 Prometheus 监控
自动化运维的魔法:使用Python脚本简化日常任务
【8月更文挑战第50天】在数字化时代的浪潮中,自动化运维成为提升效率、减少人为错误的利器。本文将通过一个实际案例,展示如何利用Python脚本实现自动化部署和监控,从而让运维工作变得更加轻松和高效。我们将一起探索代码的力量,解锁自动化运维的神秘面纱,让你的工作环境焕然一新。
137 81
|
3天前
|
Python
Python 脚本高级编程:从基础到实践
本文介绍了Python脚本的高级概念与示例,涵盖函数的灵活应用、异常处理技巧、装饰器的使用方法、上下文管理器的实现以及并发与并行编程技术,展示了Python在自动化任务和数据操作中的强大功能。包括复杂函数参数处理、自定义装饰器、上下文管理器及多线程执行示例。
29 5
|
7天前
|
安全 Python
Python脚本实现IP按段分类
【10月更文挑战第04天】
16 7
|
13天前
|
Linux UED iOS开发
Python中的自定义进度条:从零开始
Python中的自定义进度条:从零开始
|
11天前
|
机器学习/深度学习 人工智能 运维
自动化运维的魔法:如何利用Python脚本提升工作效率
【9月更文挑战第29天】在数字时代的浪潮中,IT运维人员面临着前所未有的挑战和机遇。本文将通过深入浅出的方式,介绍自动化运维的基本概念、核心价值以及使用Python脚本实现自动化任务的方法。我们将从实际案例出发,探讨如何利用Python简化日常的系统管理任务,提高运维效率,并展望自动化运维的未来趋势。无论你是初学者还是有经验的运维专家,这篇文章都将为你开启一扇通往高效工作方式的大门。
22 2
|
14天前
|
Web App开发 存储 安全
Python编写脚本,打开浏览器输入网址,自动化登陆网站
Python编写脚本,打开浏览器输入网址,自动化登陆网站
18 4
|
17天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第23天】在本文中,我们将探索如何通过编写Python脚本来自动化常见的系统管理任务,从而提升效率并减少人为错误。文章将介绍基础的Python编程概念、实用的库函数,以及如何将这些知识应用于创建有用的自动化工具。无论你是新手还是有经验的系统管理员,这篇文章都将为你提供有价值的见解和技巧,帮助你在日常工作中实现自动化。
|
19天前
|
运维 监控 安全
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第21天】在快速迭代的软件开发环境中,运维工作往往因为重复性高、易出错而被诟病。本文将介绍如何通过编写简单的Python脚本来自动化这些日常任务,从而提升效率和减少错误。我们将以实际案例为基础,展示如何从零开始构建一个自动化脚本,并解释其背后的原理。文章旨在启发读者思考如何利用编程技能来解决工作中的实际问题,进而探索技术与日常工作流程结合的可能性。
|
14天前
|
Python Windows
python之windows脚本启动bat
python之windows脚本启动bat