reporthookurllib.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,支援斷點續傳、多執行緒、更豐富進度條。urllib.request,Python 2 用 urllib。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 獲得最佳體驗。