1. 程式人生 > 程式設計 >Python HTTP下載檔案並顯示下載進度條功能的實現

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 HTTP下載檔案並顯示下載進度條功能的實現的文章就介紹到這了,更多相關python下載檔案顯示進度條內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!