美文网首页
如何在Python编程中实时显示下载进度?

如何在Python编程中实时显示下载进度?

作者: 大器待成 | 来源:发表于2020-06-18 22:58 被阅读0次

    在用Python编写批量任务、批量下载的项目中,当任务完成后需要输出任务结果,比如下载的文件数、任务名称等。一般情况下是在任务全部完成后一次性输出结果的,在此过程中会有很长一段时间没有信息输出,处于静默状态,以致于可能被认为程序没有正常运行,也无法得知当前执行到哪一步。

    为了实时可视化显示任务的运行状态,Python中可以使用文本进度条来实现。文本进度条跟图形界面相比,以极低的资源消耗便可以实现类似的功能。可用的文本进度条有以下三个:tqdmprogressbaralive-progress

    tqdm

    GitHub项目地址:https://github.com/tqdm/tqdm

    使用以下命令安装库:

    pip install tqdm
    

    典型示例1

    import time
    from tqdm import tqdm
    
    items = range(100)
    for item in tqdm(items, ascii=True): # 转为tqdm列表
        # 执行任务
        time.sleep(0.1)
    

    支持unicode的系统环境可以输出平滑实心的进度条。Windows控制台通常只部分支持unicode,因此通常需要显式地指出ascii=True。这是因为unicode字符宽度被错误显示,或者某些unicode字符不能渲染。

    大器曾经被这个问题困扰了大半个月,至此终于找到实质问题所在,在tqdm中提供参数ascii=True后问题得以完美解决。

    典型示例2

    import time
    from tqdm import tqdm
    
    items = range(100)
    with tqdm(total=len(items), desc='任务1', ascii=True) as bar:
        for item in items:
            # 执行任务
            bar.update(1)
            time.sleep(0.1)
    

    这两个示例的效果实际是差不多的,区别在于示例2中使用with语句,为tqdm提供了更多的参数,如果去掉desc参数,两者输出效果相同。desc参数可以为进度条添加前缀文字,在输出多个进度条时非常有必要,可以很直观地显示进度条的所属任务。

    tqdm01.png

    不指定ascii=True的效果如下图所示:

    tqdm02.png

    progressbar

    GitHub项目地址:https://github.com/WoLpH/python-progressbar

    使用以下命令安装库:

    pip install progressbar2
    

    典型示例1

    import time
    from progressbar import progressbar
    
    items = range(100)
    for item in progressbar(items):
        # 执行任务
        time.sleep(0.1)
    

    典型示例2

    import time
    from progressbar import *
    
    items = range(100)
    widgets = ['progress1', ': ', Percentage(), ' ', Bar('#'), ' ', Timer(), ' ', ETA(), ' ', FileTransferSpeed()]
    with ProgressBar(widgets=widgets, max_value=len(items)) as bar:
        for item in items:
            # 执行任务
            bar.update(item)
            time.sleep(0.1)
    

    widgets中的当前数与总数之比可以用Counter(format='%(value)d/%(max_value)d')

    示例2中widgets的元素可以根据自己的需要进行添加或删减。第一个元素的progress1相当于是进度条的前缀文字,唯一遗憾的是,前缀文字不能直接使用汉字,如需使用需要另外提供用到汉字的长度计算方法。有此需求的请移步GitHub,查看项目的使用说明。

    tqdm03.png

    alive-progress

    GitHub项目地址:https://github.com/rsalmei/alive-progress

    使用以下命令安装库:

    pip install alive-progress
    

    典型示例

    import time
    from alive_progress import alive_bar
    
    items = range(100)
    with alive_bar(len(items)) as bar:
        for item in items:
            # 执行任务
            bar()
            time.sleep(0.1)
    

    alive-progress的特色是有丰富的个性化的动态特效,虽然是比较简单的特效,但看起来非常有趣。此进度条适合喜欢折腾的人使用,详见GitHub项目使用说明,以下图片展示了它的部分特性。

    tqdm04.png tqdm05.png tqdm06.png

    我是大器,正在建立自己的知识库,并将这些经验分享给你,请关注我,一起交流学习。

    相关文章

      网友评论

          本文标题:如何在Python编程中实时显示下载进度?

          本文链接:https://www.haomeiwen.com/subject/npopxktx.html