直接用urllib.request.urlopen().read()下载大文件会崩,因read()将整个响应体一次性加载进内存,易触发MemoryError或OOM killer;应改用response.read(chunk_size)分块流式读取并写入文件。

为什么直接用 urllib.request.urlopen().read() 下载大文件会崩
因为 read() 会把整个响应体一次性加载进内存,下载 1GB 文件就可能吃掉 1GB 内存,还容易触发 MemoryError 或被系统 OOM killer 干掉。真实场景里,你根本不知道远程文件有多大,Content-Length 也可能缺失或不准。
用 iter_content 风格的流式读取(但 urllib 没这函数)
注意:urllib 没有 iter_content(那是 requests 的),得手动分块读。核心是用 response.read(chunk_size) 配合循环写入文件:
import urllib.request
<p>url = "<a href="https://www.php.cn/link/bbd903d446cc2f03e9061a679a550318">https://www.php.cn/link/bbd903d446cc2f03e9061a679a550318</a>"
chunk_size = 8192 # 推荐 4K–64K,太小 IO 多,太大内存压力高</p><p>with urllib.request.urlopen(url) as response:
with open("downloaded.zip", "wb") as f:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
- 必须用
with确保 response 和 file 都正确关闭,否则连接泄漏、文件损坏风险高 - 别用
response.headers.get('content-length')做循环次数判断——HTTP/1.1 分块传输、压缩、代理重写都可能导致它不可靠 - 如果服务器不支持 Range 请求,又中途断连,这段代码无法续传
加超时、重试和基础错误处理
生产环境不加超时等于裸奔;网络抖动时 URLError 或 HTTPError 很常见:
import urllib.request
import time
<p>url = "<a href="https://www.php.cn/link/0eed1b51d5c50b1f9b9de2fc705fb39f">https://www.php.cn/link/0eed1b51d5c50b1f9b9de2fc705fb39f</a>"
max_retries = 3
for attempt in range(max_retries):
try:
response = urllib.request.urlopen(url, timeout=30)</p><h1>后续流式写入逻辑...</h1><pre class="brush:php;toolbar:false;"> break
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError) as e:
if attempt == max_retries - 1:
raise e
time.sleep(2 ** attempt) # 指数退避
将测试、lint、构建和文档流程编码为命名的Python会话,以便人类和代理每次运行相同的workflow。
立即学习“Python免费学习笔记(深入)”;
-
timeout必须显式传给urlopen(),全局socket.setdefaulttimeout()不可靠 - 不要捕获
Exception,会吞掉KeyboardInterrupt等关键信号 - HTTPS 场景下,若遇到证书问题(如自签名),需额外配置
ssl_context,但绕过验证有安全风险,不建议在生产启用
需要断点续传?urllib 原生支持有限
urllib 能发 Range 请求,但不自动管理已下载字节。你需要自己检查本地文件长度,再拼 Range: bytes={start}- 头:
import os
import urllib.request
<p>local_path = "resume.zip"
url = "<a href="https://www.php.cn/link/2cc554edcbef26dedaf4004cfaf4f3d0">https://www.php.cn/link/2cc554edcbef26dedaf4004cfaf4f3d0</a>"</p><h1>检查已有文件</h1><p>headers = {}
if os.path.exists(local_path):
headers["Range"] = f"bytes={os.path.getsize(local_path)}-"</p><p>req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req) as response:
mode = "ab" if os.path.exists(local_path) else "wb"
with open(local_path, mode) as f:
for chunk in iter(lambda: response.read(8192), b""):
f.write(chunk)
- 服务器必须返回
206 Partial Content,且支持Accept-Ranges: bytes,否则会返回 200 + 全量内容,导致重复写入 - 不能只靠
Content-Range头校验完整性,大文件建议下载后比对ETag或服务端提供的 checksum - 并发下载多个大文件时,urllib 默认复用底层 socket 连接,但没内置连接池,高并发下容易耗尽本地端口
实际用 urllib 下载大文件,最常被忽略的是响应头解析的不确定性、断连后状态清理不彻底、以及误信 Content-Length 做预分配。这些地方出问题,往往表现为文件截断、磁盘写满、或程序静默卡死。

















