欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python HTTP下载文件并显示下载进度条功能的实现

时间:2021-03-25 09:19:55|栏目:Python代码|点击:

下面的Python脚本中利用request下载文件并写入到文件系统,利用progressbar模块显示下载进度条。

其中利用request模块下载文件可以直接下载,不需要使用open方法,例如:

import urllib
import requests.packages.urllib3

requests.packages.urllib3.disable_warnings()

url = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts"
urllib.urlretrieve(url, filename="hosts")

下面的例子是题目中完整的例子,其中注释的部分是进度条的另一种写法,显示当前处理过的行数。

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:        LinuxBashShellScriptForOps:download_file2.py
User:        Guodong
Create Date:    2016/9/14
Create Time:    9:40
 """
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 = ['Processed: ', progressbar.Counter(), ' lines (', progressbar.Timer(), ')']
  # pbar = progressbar.ProgressBar(widgets=widgets)
  # for chunk in pbar((i for i in response.iter_content(chunk_size=1))):
  #   if chunk:
  #     f.write(chunk)
  #     f.flush()

  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实现读取并保存文件的类

栏    目:Python代码

下一篇:Python中暂存上传图片的方法

本文标题:Python HTTP下载文件并显示下载进度条功能的实现

本文地址:http://www.codeinn.net/misctech/87812.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有