在 Python 项目中,开发完成后直接部署,如果不锁定依赖版本,很可能因为底层库升级导致代码出错。因此,写死依赖版本是保证可重复部署的最佳实践。
问题
假设你的 requirements.txt 里有:
requests
numpy
pandas如果不指定版本:
pip install -r requirements.txt- 当库发布新版本时,部署环境可能与开发环境不一致
- 可能出现 API 不兼容或行为改变的问题
Python 脚本(跨平台)
import subprocess
# 读取原始 requirements.txt
with open("requirements.txt") as f:
lines = [line.strip() for line in f if line.strip() and not line.startswith("#")]
# 获取当前环境已安装库及版本
installed = subprocess.run(["pip", "freeze"], capture_output=True, text=True).stdout.splitlines()
installed_dict = dict(line.split("==") for line in installed if "==" in line)
# 更新版本,只锁定文件中已有库
new_lines = []
for pkg in lines:
pkg_name = pkg.split("==")[0]
version = installed_dict.get(pkg_name)
if version:
new_lines.append(f"{pkg_name}=={version}")
else:
new_lines.append(pkg) # 未安装的保持原样
# 写回 requirements.txt
with open("requirements.txt", "w") as f:
f.write("\n".join(new_lines) + "\n")
print("requirements.txt 已更新为锁定版本!")Linux / macOS 一行命令(bash)
while read pkg; do
v=$(pip show $pkg | grep Version | awk '{print $2}')
if [ -n "$v" ]; then
echo "$pkg==$v"
else
echo "$pkg"
fi
done < requirements.txt > requirements.locked.txt && mv requirements.locked.txt requirements.txt
评论 (0)