Python HTTP下载文件并显示下载进度条

87 次查看 0 条评论
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
import requests
import progressbar
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
url = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts"
response = requests.request("GET", url, stream=True, data=None, headers=None)
save_path = "/tmp/hosts"
total_length = int(response.headers.get("Content-Length"))
with open(save_path, 'wb') as f:
    widgets = ['Progress: ', progressbar.Percentage(), ' ',
               progressbar.Bar(marker='#', left='[', right=']'),
               ' ', progressbar.ETA(), ' ', progressbar.FileTransferSpeed()]
    pbar = progressbar.ProgressBar(widgets=widgets, maxval=total_length).start()
    for chunk in response.iter_content(chunk_size=1):
        if chunk:
            f.write(chunk)
            f.flush()
        pbar.update(len(chunk) + 1)
    pbar.finish()

相关文章:

Python带进度条文件下载示例

Other none

暂无评论,快来抢沙发。