萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python urllib.urlretrieve 顯示下載進度條:reporthook 回調實作

核心參數:reporthook

urllib.request.urlretrieve(url, filename, reporthook) 每下載一塊資料呼叫一次 reporthook(count, block_size, total_size)。

進度條回調函式

import sys
import urllib.request

def reporthook(count, block_size, total_size):
    """count: 已下載塊數, block_size: 塊大小, total_size: 總大小(-1 未知)"""
    if total_size <= 0:
        # 無法取得總大小,僅顯示已下載量
        sys.stdout.write(f"\r已下載: {count * block_size:,} bytes")
    else:
        percent = min(100, count * block_size * 100 // total_size)
        bar_len = 40
        filled = bar_len * percent // 100
        bar = '█' * filled + '░' * (bar_len - filled)
        sys.stdout.write(f"\r[{bar}] {percent:3d}% ({count * block_size:,} / {total_size:,} bytes)")
    sys.stdout.flush()

# 使用範例
url = "https://speed.hetzner.de/100MB.bin"
dest = "100MB.bin"
print(f"下載: {url}")
urllib.request.urlretrieve(url, dest, reporthook=reporthook)
print("\n下載完成!")

輸出效果示意

下載: https://speed.hetzner.de/100MB.bin
[████████████████████░░░░░░░░░░░░]  52% (52,428,800 / 100,000,000 bytes)
[████████████████████████████████████████] 100% (100,000,000 / 100,000,000 bytes)
下載完成!

注意事項

  • total_size = -1 時伺服器未提供 Content-Length,僅能顯示已下載位元組數。
  • 大檔案建議用 requests + tqdm,支援斷點續傳、多執行緒、更豐富進度條。
  • Python 3 使用 urllib.request,Python 2 用 urllib。

進階:tqdm 一行搞定

from tqdm import tqdm
import urllib.request

with tqdm(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, desc="Downloading") as pbar:
    urllib.request.urlretrieve(url, dest, reporthook=lambda c, b, t: pbar.update(b))

結語

reporthook 是 urlretrieve 唯一的進度回調介面。手寫進度條適合零依賴腳本;專案中請直接用 requests + tqdm 或 aiohttp + tqdm.asyncio 獲得最佳體驗。

copyright © 萬盛學電腦網 all rights reserved