哈哈,其实关于进度条的总结,很多博主都已经写过了,总结的非常好,不过想了想还是结合自己编写命令行工具的实际情况出发写下自己的感受。
•自己使用time
和sys
模块结合循环实现•PyPrind[1] 526 star, 许久不更新了•python-progressbar[2] 353 star, 许久不更新了•progress[3] 850 star, 最后一次更新12个月前•tqdm[4] 14.8k star, 截止写文档还在更新•alive_progress[5] 610 star, 持续更新中•rich[6] 7k star, 持续更新中•rich并不单单局限于进度条,这是一个功能强大的命令行辅助,官方介绍: Rich is a Python library for rich text and beautiful formatting in the terminal•click_spinner[7] 157 star, 3个月前最后一次更新
•click[8] 很牛逼的工具,对Flask
, Django
都有与之对应的模块实现,周边插件很丰富,我写命令行工具都是使用这个,也是实现了自己的progressbar,不过我基本都是搭配tqdm
使用。•typer[9] 大家应该听过FastAPI
吧,同一个作者的作品,非常优秀的命令行工具框架,也是实现了自己的progressbar,最近写的一个工具是基于这个命令行框架来写的,个人感受是还有待于完善。
这个工具包没怎么用过。
# pip install pyprind
import pyprind
for i in pyprind.prog_bar(range(n)):
time.sleep(timesleep) # your computation here
这个工具包没怎么用过。
from progressbar import *
import time
progress = ProgressBar()
for i in progress(range(80)):
time.sleep(0.01)
widgets = ['Something: ', Percentage(), ' ', Bar(marker=RotatingMarker()),
' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets, maxval=10000000).start()
for i in range(1000000):
# do something
pbar.update(10*i+1)
pbar.finish()
这个工具包没怎么用过。
# pip install progress
from progress.bar import Bar
with Bar('Processing', max=20) as bar:
for i in range(20):
# Do some work
bar.next()
这个工具包算是用的最多的一个。
# pip install tqdm
from tqdm import trange
for i in trange(100):
sleep(0.01)
# pip install alive-progress
from alive_progress import alive_bar
items = range(1000) # retrieve your set of items
with alive_bar(len(items)) as bar: # declare your expected total
for item in items: # iterate as usual
# process each item
bar() # call after consuming one item
这个工具包可以减少很大的代码量,表格输出,markdown格式输出,日志格式化输出等等,十分强大,值得学习。
# pip install rich
from rich.progress import track
for step in track(range(100)):
do_step(step)
这个工具包很实用,在我们编写工具的时候,有的时候不太好评估需要花费多长时间,这个时候可以选择使用click-spinner,避免让用户干等。
# pip install click-spinner
with click_spinner.spinner():
do_something()
do_something_else()
How to Use Progress Bars in Python [10]
给Python代码加上酷炫进度条的几种姿势
其实还有很多没有列举到的命令行工具,都是蛮强大的,我个人编写命令行工具的习惯是click + tqdm + colorama这些工具组合实现,当然了,每个人的习惯不同,这里只是列出了我个人常用的,其他的点可能就是格式化输出 + 自动补全 +
命令行框架我们后续抽一个文档专门介绍下吧,可选择性还是蛮大的,可千万别挑花了眼。
很多时候我们写命令行工具是为了便于管理,但是python的话如何更好的多人协同或者使用呢,比如你写了一个工具,如何给你的小伙伴用呢,如何推广全组呢,总不能发代码给别人,然后clone下来进行pip install -r requirements.txt
吧,这样做有些低效,而且不便于维护更新,后续我们会针对这块讲解下。
[1]
PyPrind: https://github.com/rasbt/pyprind
[2]
python-progressbar: https://github.com/niltonvolpato/python-progressbar
[3]
progress: https://github.com/verigak/progress/
[4]
tqdm: https://github.com/tqdm/tqdm
[5]
alive_progress: https://github.com/rsalmei/alive-progress
[6]
rich: https://github.com/willmcgugan/rich
[7]
click_spinner: https://github.com/click-contrib/click-spinner
[8]
click: https://github.com/pallets/click
[9]
typer: https://github.com/tiangolo/typer
[10]
How to Use Progress Bars in Python : https://towardsdatascience.com/learning-to-use-progress-bars-in-python-2dc436de81e5