Python几种酷炫的进度条的方式


Posted in Python onApril 11, 2022

前言:

在下载某些文件的时候你一定会不时盯着进度条,在写代码的时候使用进度条可以便捷的观察任务处理情况。

除了使用 print 来打印之外,今天本文我来给大家介绍几种酷炫的进度条的方式。

Python几种酷炫的进度条的方式

1、自定义ProgressBar

最原始的办法就是不借助任何第三方工具,自己写一个进度条函数,使用time模块配合sys模块即可

import sys
import time

def progressbar(it, prefix="", size=60, file=sys.stdout):
    count = len(it)
    def show(j):
        x = int(size*j/count)
        file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
        file.flush()        
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    file.write("\n")
    file.flush()

    
for i in progressbar(range(15), "Computing: ", 40):
    do_something()
    time.sleep(0.1)

Python几种酷炫的进度条的方式

自己定义的好处就是可以将进度条定义成我们想要的形式比如上面就是使用#与·来输出,为什么不用print?因为sys.stdout就是print的一种默认输出格式,而sys.stdout.write()可以不换行打印,sys.stdout.flush()可以立即刷新输出的内容。当然也可以封装成类来更好的使用,但效果是类似的。

from __future__ import print_function
import sys
import re


class ProgressBar(object):
    DEFAULT = 'Progress: %(bar)s %(percent)3d%%'
    FULL = '%(bar)s %(current)d/%(total)d (%(percent)3d%%) %(remaining)d to go'

    def __init__(self, total, width=40, fmt=DEFAULT, symbol='=',
                 output=sys.stderr):
        assert len(symbol) == 1

        self.total = total
        self.width = width
        self.symbol = symbol
        self.output = output
        self.fmt = re.sub(r'(?P<name>%\(.+?\))d',
            r'\g<name>%dd' % len(str(total)), fmt)

        self.current = 0

    def __call__(self):
        percent = self.current / float(self.total)
        size = int(self.width * percent)
        remaining = self.total - self.current
        bar = '[' + self.symbol * size + ' ' * (self.width - size) + ']'

        args = {
            'total': self.total,
            'bar': bar,
            'current': self.current,
            'percent': percent * 100,
            'remaining': remaining
        }
        print('\r' + self.fmt % args, file=self.output, end='')

    def done(self):
        self.current = self.total
        self()
        print('', file=self.output)
        
from time import sleep

progress = ProgressBar(80, fmt=ProgressBar.FULL)

for x in range(progress.total):
    progress.current += 1
    progress()
    sleep(0.1)
progress.done()

Python几种酷炫的进度条的方式

2、tqdm

之前我们说了,自定义的好处就是可以自己修改,那么使用第三方库的好处就是可以偷懒,不用自己写,拿来就能用。比如提到Python进度条那肯定会想到常用的tqdm,安装很简单pip install tqdm即可,使用也很简单,几行代码即可实现上面的进度条

from tqdm import trange
import time
for i in trange(10): 
    time.sleep(1)

Python几种酷炫的进度条的方式

当然tqdm作为老牌的Python进度条工具,循环处理、多进程、多线程、递归处理等都是支持的,你可以在官方GitHub上学习 、解锁更多的玩法。

3、Rich

上面两种实现Python进度条的方法都学会了吗,虽然简单但是看上去并不漂亮,颜色也比较单调。所以最后压轴出场的就是一款比较小众的第三方库Rich 。Rich主要是用于在终端中打印丰富多彩的文本(最高支持1670万色)

Python几种酷炫的进度条的方式

所以当然可以使用Rich打印进度条,显示完成百分比,剩余时间,数据传输速度等都可以。并且样式更加酷炫,并且它是高度可配置的,因此我们可以对其进行自定义以显示所需的任何信息。使用也很简单,比如我们使用Rich来实现一个最简单的进度条

from rich.progress import track
import  time

for step in track(range(30)):
    time.sleep(0.5)

Python几种酷炫的进度条的方式

同时Rich支持多个进度条,这在多任务情况下监控的进度很有用

Python几种酷炫的进度条的方式

Python 相关文章推荐
处理Python中的URLError异常的方法
Apr 30 Python
在Python中用split()方法分割字符串的使用介绍
May 20 Python
python调用API实现智能回复机器人
Apr 10 Python
Python中将dataframe转换为字典的实例
Apr 13 Python
详解Python locals()的陷阱
Mar 26 Python
python制作图片缩略图
Apr 30 Python
python绘制多个子图的实例
Jul 07 Python
Django中提示消息messages的设置方式
Nov 15 Python
python中return的返回和执行实例
Dec 24 Python
QML实现钟表效果
Jun 02 Python
python装饰器三种装饰模式的简单分析
Sep 04 Python
python中使用asyncio实现异步IO实例分析
Feb 26 Python
Python通过loop.run_in_executor执行同步代码 同步变为异步
Python Pandas解析读写 CSV 文件
宝塔更新Python及Flask项目的部署
python模板入门教程之flask Jinja
使用Python解决图表与画布的间距问题
Python的property属性详细讲解
Apr 11 #Python
OpenCV项目实践之停车场车位实时检测
You might like
php smarty 二级分类代码和模版循环例子
2011/06/01 PHP
php随机显示图片的简单示例
2014/02/15 PHP
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
JS处理VBArray的函数使用说明
2008/05/11 Javascript
一个很酷的拖动层的js类,兼容IE及Firefox
2009/06/23 Javascript
js小数运算出现多位小数如何解决
2015/10/08 Javascript
基于JavaScript实现本地图片预览
2017/02/08 Javascript
layui表格实现代码
2017/05/20 Javascript
vue路由跳转时判断用户是否登录功能的实现
2017/10/26 Javascript
Vue中的Vux配置指南
2017/12/08 Javascript
VUE实现强制渲染,强制更新
2019/10/29 Javascript
node.js使用http模块创建服务器和客户端完整示例
2020/02/10 Javascript
[02:57]2014DOTA2国际邀请赛 选手辛苦解说更辛苦
2014/07/10 DOTA
[01:14]英雄,所敬略同——2018完美盛典宣传视频4K
2018/12/05 DOTA
详解Python中的日志模块logging
2015/06/19 Python
Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能
2018/01/11 Python
Python3使用pandas模块读写excel操作示例
2018/07/03 Python
情人节快乐! python绘制漂亮玫瑰
2020/08/18 Python
python使用Plotly绘图工具绘制散点图、线形图
2019/04/02 Python
python基于pdfminer库提取pdf文字代码实例
2019/08/15 Python
python 如何去除字符串头尾的多余符号
2019/11/19 Python
Python捕获异常堆栈信息的几种方法(小结)
2020/05/18 Python
opencv 查找连通区域 最大面积实例
2020/06/04 Python
使用Keras 实现查看model weights .h5 文件的内容
2020/06/09 Python
opencv 图像加法与图像融合的实现代码
2020/07/08 Python
印尼购物网站:iLOTTE
2019/10/16 全球购物
汉米尔顿手表官网:Hamilton
2020/09/13 全球购物
本科生详细的自我评价
2013/09/19 职场文书
省级优秀班集体申报材料
2014/05/25 职场文书
大四优秀党员个人民主评议
2014/09/19 职场文书
公民代理授权委托书
2014/09/24 职场文书
安全生产月标语
2014/10/07 职场文书
2014年煤矿工人工作总结
2014/12/08 职场文书
终止解除劳动合同证明书
2015/06/17 职场文书
如何写观后感
2015/06/19 职场文书
2015年学校远程教育工作总结
2015/07/20 职场文书