使用 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,參數相同。