如何编写脚本获取特定Python版本兼容的指定库可用版本列表?
获取特定Python版本兼容的PyPI库版本列表
实现思路
直接调用PyPI的JSON API获取目标库的全量版本信息,解析每个版本的requires_python约束字段,筛选出与指定Python版本兼容的版本。核心依赖Python标准库+packaging模块(用于处理版本约束逻辑)。
示例脚本
import urllib.request import json from packaging.specifiers import SpecifierSet from packaging.version import Version def get_compatible_versions(package_name: str, python_version: str) -> list: # 调用PyPI API拉取包的完整版本数据 api_url = f"https://pypi.org/pypi/{package_name}/json" try: with urllib.request.urlopen(api_url) as resp: package_data = json.load(resp) except urllib.error.HTTPError as err: print(f"拉取包信息失败: {err}") return [] compatible_versions = [] # 遍历所有已发布版本 for ver_str, release_details in package_data["releases"].items(): # 跳过无发布文件的无效版本 if not release_details: continue # 获取该版本的Python版本约束 py_constraint = release_details[0]["requires_python"] if not py_constraint: # 未指定约束的版本默认视为兼容 compatible_versions.append(ver_str) continue # 校验目标Python版本是否符合约束 spec_set = SpecifierSet(py_constraint) if Version(python_version) in spec_set: compatible_versions.append(ver_str) # 按版本号从新到旧排序 compatible_versions.sort(key=Version, reverse=True) return compatible_versions if __name__ == "__main__": # 示例:查询Python 3.8兼容的numpy版本 target_package = "numpy" target_py_version = "3.8" matched_versions = get_compatible_versions(target_package, target_py_version) if matched_versions: print(f"与Python {target_py_version}兼容的{target_package}版本(从新到旧):") for idx, ver in enumerate(matched_versions, 1): print(f"{idx}. {ver}") else: print(f"未找到与Python {target_py_version}兼容的{target_package}版本")
使用说明
- 先安装依赖:
pip install packaging - 修改脚本中
target_package和target_py_version为你需要的库名和Python版本 - 运行脚本即可得到兼容版本列表
注意事项
- 部分老旧版本可能未在PyPI标注
requires_python字段,脚本默认将其归为兼容范畴,若需更严格筛选可自行调整逻辑 - 确保网络正常,能够访问PyPI的API接口
内容的提问来源于stack exchange,提问作者Bosser445
相关产品推荐
相关产品推荐

