• 技术文章 >Python技术 >Python基础教程

    Python中的进度条progressbar,让进度直观显示!

     Ly Ly2020-06-22 17:11:37转载6199

    今天突然被问了一个问题:程序在执行中很久不结束是怎么回事?看不到程序执行的进度,在我们进行大工程的时候的确是一件很头疼的事,本文让我们来了解一个很常用的进度条展示小工具——Progressbar。

    注:最新版的使用者不要照着GitHub上的官方文档去操作,文档信息没有维护,会出现很多问题。

    下载模块

    1

    pip install progressbar

    注意:安装模块的时候可能会出现warning,耐心等待,总会出现success。

    简单的使用方法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    import time

    from progressbar import *

      

    total = 1000

      

    def test_func():

        time.sleep(0.01)

    progress = ProgressBar()

    for i in progress(range(1000)):

        test_func()

    对于简单的循环函数而言,我们只需要把它加在我们组合了progress方法的循环下就可以了。

    我们会看到如下的进度条:

    cd612bc8cff019d2fd62e1fe7a06a71.png放在循环外定义使用

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    # -*- coding=utf-8 -*-

    from __future__ import division

    import sys, time

    from progressbar import *

    total = 1000

    def test_func():

        time.sleep(0.01)

    bar = ProgressBar().start()

    for i in range(1000):

        bar.update(int((i / (total - 1)) * 100))

        test_func()

    bar.finish()

    注意:不要忽略了start()和fininsh()否则会出现问题。

    多层信息的展示使用

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    # -*- coding=utf-8 -*-

    import time

    from progressbar import *

    total = 1000

    def test_func():

        time.sleep(0.01)

    widgets = [

        'Progress: ',

        Percentage(), ' ',

        Bar('#'), ' ',

        Timer(), ' ',

        ETA(), ' ',

        FileTransferSpeed()

    ]

    bar = ProgressBar(widgets=widgets, maxval=10 * total).start()

    for i in range(total):

        bar.update(10 * i + 1)

        test_func()

    bar.finish()

    结果如下:

    a67d2a27d347bf6c82460f61f4c9154.png参数说明:

    'Progress: ' :设置进度条前显示的文字

    Percentage() :显示百分比

    Bar('#') :设置进度条形状

    ETA() :显示预计剩余时间

    Timer() :显示已用时间

    更多Python知识,请关注Python视频教程!!

    专题推荐:python
    上一篇:Python之了解pandas! 下一篇:2020了,你该会用seaborn了!

    相关文章推荐

    • Python中的时间模块大汇总!• Python如何处理Excel中的数据• python如何建立venv虚拟环境

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网