python 实现下载进度条的方法

第一种(简单).python实现简单的进度条的方法

import sys
for i in range(101):
    s="\r%d%% %s"%(i,"#"*i)   #\r表示回车但是不换行,利用这个原理进行百分比的刷新
    sys.stdout.write(s)       #向标准输出终端写内容
    sys.stdout.flush()        #立即将缓存的内容刷新到标准输出
    import time
    time.sleep(0.1)           #设置延迟查看效果

第二种(复杂/美观)(推荐):

#!/usr/bin/python3
# -*- coding:utf-8 -*-
 
import sys
import time
from urllib import request
 
 
'''
 urllib.urlretrieve 的回调函数:
def callbackfunc(blocknum, blocksize, totalsize):
    @blocknum:  已经下载的数据块
    @blocksize: 数据块的大小
    @totalsize: 远程文件的大小
'''
 
def Schedule(blocknum, blocksize, totalsize):
    speed = (blocknum * blocksize) / (time.time() - start_time)
    # speed_str = " Speed: %.2f" % speed
    speed_str = " Speed: %s" % format_size(speed)
    recv_size = blocknum * blocksize
     
    # 设置下载进度条
    f = sys.stdout
    pervent = recv_size / totalsize
    percent_str = "%.2f%%" % (pervent * 100)
    n = round(pervent * 50)
    s = ('#' * n).ljust(50, '-')
    f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str)
    f.flush()
    # time.sleep(0.1)
    f.write('\r')
 
# 字节bytes转化K\M\G
def format_size(bytes):
    try:
        bytes = float(bytes)
        kb = bytes / 1024
    except:
        print("传入的字节格式不对")
        return "Error"
    if kb >= 1024:
        M = kb / 1024
        if M >= 1024:
            G = M / 1024
            return "%.3fG" % (G)
        else:
            return "%.3fM" % (M)
    else:
        return "%.3fK" % (kb)
 
if __name__ == '__main__':
    # print(format_size(1222222222))
    start_time = time.time()
    filename = 'test.data'
    url = 'http://ip:port/path/speed.test'
    request.urlretrieve(url, filename, Schedule)

小提示:第二种注意把time.sleep(0.1)打开,不然看不到下载的时候可能看不到进度条

参考链接:https://yq.aliyun.com/articles/548109

                  https://www.cnblogs.com/standby/p/7384187.html

猜你喜欢

转载自www.cnblogs.com/fh-fendou/p/10524856.html