You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python不安装包即可查询requirements.txt中包的最新版本及依赖

实现方案

核心思路

  • 直接调用PyPI官方提供的公开元数据JSON接口,无需下载/安装任何目标查询包,也无需依赖shell命令
  • 仅需Python标准库即可完成请求发送、数据解析,无需额外安装第三方查询工具

完整实现代码

import json
from urllib.request import urlopen
from urllib.error import HTTPError

def get_pypi_package_info(package_name: str) -> dict:
    """
    从PyPI获取指定包的最新版本号和依赖项
    返回空字典表示查询失败(通常是包名错误)
    """
    base_url = f"https://pypi.org/pypi/{package_name.strip()}/json"
    try:
        with urlopen(base_url, timeout=10) as resp:
            data = json.loads(resp.read().decode('utf-8'))
        latest_version = data['info']['version']
        dependencies = data['info']['requires_dist'] or []
        # 过滤掉依赖中的环境标记可选内容,只保留核心依赖名和版本限制(可根据需求调整)
        clean_deps = []
        for dep in dependencies:
            # 去掉分号后面的环境限制、方括号里的额外依赖标记
            core_dep = dep.split(';')[0].split('[')[0].strip()
            if core_dep not in clean_deps:
                clean_deps.append(core_dep)
        return {
            "package_name": package_name,
            "latest_version": latest_version,
            "dependencies": clean_deps
        }
    except HTTPError as e:
        if e.code == 404:
            print(f"警告:包 {package_name} 在PyPI不存在,请检查包名是否正确(注意导入名和PyPI包名可能不同,比如opencv对应PyPI包名为opencv-python)")
        else:
            print(f"查询包 {package_name} 失败,错误码:{e.code}")
        return {}
    except Exception as e:
        print(f"查询包 {package_name} 发生未知错误:{str(e)}")
        return {}

if __name__ == "__main__":
    # 读取requirements.txt
    with open("requirements.txt", "r", encoding="utf-8") as f:
        packages = [line.strip() for line in f if line.strip() and not line.startswith('#')]
    
    result = []
    for pkg in packages:
        pkg_info = get_pypi_package_info(pkg)
        if pkg_info:
            result.append(pkg_info)
    
    # 打印结果
    for item in result:
        print(f"\n包名:{item['package_name']}")
        print(f"最新版本:{item['latest_version']}")
        print("依赖项:")
        for dep in item['dependencies']:
            print(f"- {dep}")

注意事项

  • 你给出的依赖列表中的opencv不是PyPI官方包名,对应正确的包名为opencv-python,查询前需要替换否则会返回404
  • 如果不需要过滤依赖的环境标记和额外依赖,可以去掉代码中对dependencies的清洗逻辑,直接返回原始的requires_dist内容
  • 代码全程使用Python标准库实现,不需要额外安装任何第三方工具,也不会下载安装你要查询的任意依赖包

内容的提问来源于stack exchange,提问作者DSH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:05