【python小工具】requests下载大文件,可代理,可续载

import requests
import time
from datetime import timedelta

# 配置代理
# os.environ['http_proxy'] = "socks5://127.0.0.1:8888"
# os.environ['https_proxy'] = "socks5://127.0.0.1:8888"

def download(name, url, headers={}, interval=0.5):
    def MB(byte):
        return byte / 1024 / 1024
    def seconds_to_time(seconds):
        return str(timedelta(seconds=seconds)).split('.')[0]
    print(name)

    local_file_size = os.path.getsize(name) if os.path.exists(name) else 0
    headers={
        **headers,
        'Proxy-Connection': 'keep-alive',
        'Range': 'bytes=%d-' % local_file_size
    }
    res = requests.get(url, stream=True, headers=headers})
    file_size = int(res.headers['content-length']) + local_file_size # 文件大小 Byte
    print('文件大小: %d MB' % MB(file_size))
    f = open(name, 'ab')
    down_size = local_file_size  # 已下载字节数
    old_down_size = local_file_size  # 上一次已下载字节数
    time_ = time.time()
    for chunk in res.iter_content(chunk_size=1024*1024):
        if chunk:
            f.write(chunk)
            down_size += len(chunk)
            cost_time = time.time() - time_
            if cost_time > interval:
                # rate = down_size / file_size * 100  # 进度  0.01%
                speed = (down_size - old_down_size) / cost_time  # 速率 0.01B/s
                
                old_down_size = down_size
                time_ = time.time()
                
                print_params = [MB(speed), MB(down_size), MB(file_size), seconds_to_time((file_size - down_size) / speed])
                print('\r{:.2f}MB/s - {:.2f}MB,共 {:.2f}MB,还剩 {}   '.format(*print_params), end='')
                
    f.close()
    print('\r下载成功'+' '*50)
   
download('qq.exe', 'https:down.qq.com/qqweb/PCQQ/PCQQ_EXE/PCQQ2021.exe')

# output
qq.exe
0.27MB/s - 59.00MB,共 84.54MB,还剩 1:00:37

你可能感兴趣的:(python小工具,python)