30

几行代码就可以轻松给你的程序加上进度条

 3 years ago
source link: http://developer.51cto.com/art/202009/627291.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

迷人的进度条

进度条是一个过程剩余时间的可视化表示。它们使您不必担心进程是否挂起,也不必尝试预测代码的进展情况。您可以实时直观地看到脚本进行得有多好!

Jj6RF3m.gif!mobile

如果您以前从未考虑过或使用过进度条,那么很容易认为它们会给您的代码增加不必要的复杂性,并且很难维护。这与事实相去甚远。通过几行代码,我们将看到如何向命令行脚本添加进度条。

8b3f2afe1af65f9190dcc23949e9af74.jpeg

使用Progress库

首先要使用的python库是Progress。

您所需要做的就是定义您希望进行的迭代次数、bar的类型,并在每次迭代时让bar知道。

import timefrom progress.bar import IncrementalBarmylist = [1,2,3,4,5,6,7,8]bar = IncrementalBar('Countdown', max = len(mylist))for item in mylist: bar.next() time.sleep(1)bar.finish()

运行结果

BjAzuu.gif!mobile

如果你不喜欢进度条的格式,有很多可供你选择:

QR77raQ.gif!mobile

使用tqdm库

接下来要介绍的是tqdm库。

用于Python和CLI的快速、可扩展的进度条

就像我们看到的上一个库一样,我们可以用几行代码引入一个progres条。在设置上只有细微的差别:

import timefrom tqdm import tqdmmylist = [1,2,3,4,5,6,7,8]for i in tqdm(mylist): time.sleep(1)

运行结果:

M7Rrqmu.gif!mobile

使用Alive Progress库

顾名思义,这个库试图激活进度条。它比我们之前看到的进度条有更多的动画。但是在代码方面,它非常相似:

from alive_progress import alive_barimport timemylist = [1,2,3,4,5,6,7,8]with alive_bar(len(mylist)) as bar: for i in mylist: bar() time.sleep(1)

QN3MBvf.gif!mobile

使用PySimpleGUI的图形化进度条

我们可以添加一行代码来将图形化的进度条添加到命令行脚本中。

VbUbe2u.gif!mobile

要实现上述目标,我们所需要的是:

import PySimpleGUI as sgimport timemylist = [1,2,3,4,5,6,7,8]for i, item in enumerate(mylist): sg.one_line_progress_meter('This is my progress meter!', i+1, len(mylist), '-key-') time.sleep(1)

【责任编辑:赵宁宁 TEL:(010)68476606】


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK