Python HTTP下載文件并顯示下載進度條功能的實現(xiàn)
下面的Python腳本中利用request下載文件并寫入到文件系統(tǒng),利用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")
下面的例子是題目中完整的例子,其中注釋的部分是進度條的另一種寫法,顯示當前處理過的行數(shù)。
#!/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()
運行結(jié)果:
到此這篇關(guān)于Python HTTP下載文件并顯示下載進度條功能的實現(xiàn)的文章就介紹到這了,更多相關(guān)python下載文件顯示進度條內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用Python實現(xiàn)定時備份Mongodb數(shù)據(jù)并上傳到FTP服務器
這篇文章主要介紹了用Python實現(xiàn)定時備份Mongodb數(shù)據(jù)并上傳到FTP服務器,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01python之線程池map()方法傳遞多參數(shù)list
這篇文章主要介紹了python之線程池map()方法傳遞多參數(shù)list問題,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03使用python快速在局域網(wǎng)內(nèi)搭建http傳輸文件服務的方法
這篇文章主要介紹了使用 python快速在局域網(wǎng)內(nèi)搭建http傳輸文件服務,但是這種方法不要傳輸機密文件,安全性不高,只用到http協(xié)議沒有使用任何加密協(xié)議,具體實現(xiàn)方法跟隨小編一起看看吧2019-11-11