python 断点续传下载

示例代码: 

# -*- coding:utf-8 -*-
import sys
import requests
import os

requests.packages.urllib3.disable_warnings()


def download(url, file_path):
    r1 = requests.get(url, stream=True, verify=False)  # stream=True将读取到达时的数据,无论数据的大小是  接收块。 如果stream=False,则数据返回为  单个块。

    if r1.status_code == 403:
        raise Exception("Download Failed: %s" % url)

    total_size = int(r1.headers["Content-Length"])

    # local file
    if os.path.exists(file_path):
        temp_size = os.path.getsize(file_path)
    else:
        temp_size = 0

    print("已经下载完成的的大小 = {}".format(temp_size))
    print("总大小 = {}".format(total_size))

    headers = {"Range": "bytes=%d-" % temp_size}
    r = requests.get(url, stream=True, verify=False, headers=headers)

    with open(file_path, "ab") as f:
        for chunk in r.iter_content(chunk_size=1024):  # chunk_size设置大点,下载快
            import time; time.sleep(1)  # sleep 为了展示进度,减慢进度的更新
            if chunk:
                temp_size += len(chunk)
                f.write(chunk)
                f.flush()

                done = int(50 * temp_size / total_size)
                sys.stdout.write("\r[%s%s] %d%%" % ('*' * done, ' '*(50- done), 100*temp_size/total_size))
                sys.stdout.flush()

    print('--- end ---')


if __name__ == '__main__':
    url ="http://pypi.doubanio.com/packages/2d/d3/41b3db87f262debadb153900d4e6f8d61aa87187dd6fedd855ed24e8526d/rsa-4.7.1.tar.gz"  # 替换为要下载的地址
    path="./rsa-4.7.1.tar.gz"  # 替换为要下载的名称
    download(url, path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值