栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

下面的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 HTTP下载文件并显示下载进度条功能的实现的文章就介绍到这了,更多相关python下载文件显示进度条内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/20164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号