如何检查Python项目中固定版本的依赖是否有可用更新?
实现思路
1. 解析依赖文件提取包名与本地版本
首先读取pyproject.toml文件,解析其中的依赖项:
- 用
toml库加载文件内容,定位到project.dependencies字段; - 通过正则或字符串拆分,从
包名 == 版本号格式的依赖规则里提取包名和固定版本; - 跳过不符合固定版本格式的依赖(如果有)。
示例代码片段:
import toml import re def parse_dependencies(filepath): with open(filepath, 'r') as f: pyproject_data = toml.load(f) dependencies = pyproject_data['project']['dependencies'] dep_map = {} # 正则匹配固定格式的依赖 pattern = re.compile(r'^([a-zA-Z0-9\-_]+)\s*==\s*([0-9a-zA-Z\.\-]+)$') for dep in dependencies: match = pattern.match(dep) if match: pkg_name, version = match.groups() dep_map[pkg_name] = version return dep_map
2. 查询PyPI获取包的最新版本
通过PyPI官方JSON接口查询每个包的最新版本:
- 构造请求URL:
https://pypi.org/pypi/{pkg_name}/json; - 用
requests库发送GET请求,解析返回的JSON数据,提取info.version字段; - 加入异常处理,应对网络故障、包不存在等情况。
示例代码片段:
import requests def get_latest_version(pkg_name): url = f"https://pypi.org/pypi/{pkg_name}/json" try: response = requests.get(url, timeout=10) response.raise_for_status() return response.json()['info']['version'] except (requests.exceptions.RequestException, KeyError): return None
3. 版本号对比与结果输出
用packaging库的Version类处理版本号比较(避免手动处理复杂版本规则):
- 将本地版本和最新版本转换为
Version实例; - 若本地版本小于最新版本,输出提示信息;否则标记为已更新。
示例代码片段:
from packaging.version import Version def check_dependencies(filepath): dep_map = parse_dependencies(filepath) for pkg_name, local_version in dep_map.items(): latest_version = get_latest_version(pkg_name) if not latest_version: print(f"无法获取{pkg_name}的最新版本") continue try: local_ver = Version(local_version) latest_ver = Version(latest_version) if local_ver < latest_ver: print(f"You have {pkg_name} '{local_version}' but '{latest_version}' is available") else: print(f"{pkg_name} '{local_version}' 已是最新版本") except ValueError: print(f"{pkg_name}的版本格式无效:{local_version} 或 {latest_version}")
4. 函数整合与调用
将上述步骤整合到目标函数中:
def check_for_out_of_date_dependencies(pyproject_toml_filepath): check_dependencies(pyproject_toml_filepath) # 调用示例 check_for_out_of_date_dependencies("pyproject.toml")
注意事项
- 需提前安装依赖库:
pip install toml requests packaging; - 若依赖文件是
requirements.txt格式,只需修改解析函数逻辑,逐行读取并拆分包名和版本; - 可改用异步请求(如
aiohttp)优化批量查询的速度。
内容的提问来源于stack exchange,提问作者MYK
相关产品推荐
相关产品推荐

