首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 下載檔案顯示進度條實作

     編輯:更多程式設計知識

使用 urllib.urlretrieve 的 reporthook 回呼函式,即可即時顯示下載進度百分比。

import sys
import urllib

def report(count, block_size, total_size):
    percent = int(count * block_size * 100 / total_size)
    sys.stdout.write('\r%d%% complete' % percent)
    sys.stdout.flush()

url = 'https://example.com/largefile.zip'
filename = 'largefile.zip'
sys.stdout.write('Fetching %s...\n' % filename)
urllib.urlretrieve(url, filename, reporthook=report)
sys.stdout.write('\rDownload complete, saved as %s\n\n' % filename)
sys.stdout.flush()

關鍵點

  • count:已下載區塊數
  • block_size:區塊大小(bytes)
  • total_size:檔案總大小
  • 使用 \r 回到行首覆寫,配合 flush() 即時刷新終端機輸出

此法適用於 Python 2;Python 3 請改用 urllib.request.urlretrieve,參數相同。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved