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

如何查询当前Django及pip依赖可兼容的最高Python版本?

查询当前pip依赖兼容的最高Python版本脚本

核心思路

遍历当前环境已安装的所有pip包,获取每个包已安装版本对应的Python兼容范围,最终找出所有包都支持的最高Python版本。

前置依赖

先安装处理版本约束的工具库:

pip install packaging

实现脚本

import subprocess
import json
from packaging.specifiers import SpecifierSet
from packaging.version import Version

def get_installed_packages():
    # 获取当前环境已安装的所有包及其版本
    result = subprocess.run(
        ["pip", "list", "--format", "json"],
        capture_output=True,
        text=True,
        check=True
    )
    return json.loads(result.stdout)

def get_package_python_requirements(package_name, package_version):
    # 获取指定包版本的Python版本要求
    try:
        result = subprocess.run(
            ["pip", "show", "-f", package_name],
            capture_output=True,
            text=True,
            check=True
        )
        output = result.stdout
        # 提取Requires-Python字段
        for line in output.splitlines():
            if line.startswith("Requires-Python:"):
                return line.split(":", 1)[1].strip()
        # 无声明则默认兼容所有版本
        return ""
    except subprocess.CalledProcessError:
        print(f"⚠️ 无法获取包 {package_name}@{package_version} 的兼容性信息,默认视为兼容所有版本")
        return ""

def find_highest_compatible_python():
    # 定义待检查的Python版本(从高到低排序,可按需扩展)
    python_version_candidates = [
        "3.12", "3.11", "3.10", "3.9", "3.8", "3.7"
    ]
    version_objs = [Version(v) for v in python_version_candidates]
    
    installed_packages = get_installed_packages()
    package_specifiers = []
    
    for pkg in installed_packages:
        req_py = get_package_python_requirements(pkg["name"], pkg["version"])
        if req_py:
            package_specifiers.append(SpecifierSet(req_py))
    
    # 从高到低检查,找到第一个所有包都兼容的版本
    for py_version in version_objs:
        all_compatible = True
        for spec in package_specifiers:
            if py_version not in spec:
                all_compatible = False
                break
        if all_compatible:
            return str(py_version)
    
    # 无匹配时返回当前使用的版本
    return "3.7.5"

if __name__ == "__main__":
    highest_compatible = find_highest_compatible_python()
    print(f"✅ 无需变更pip模块即可使用的最高Python版本是: {highest_compatible}")

使用说明

  1. 在你当前的Python 3.7.5环境中运行这个脚本
  2. 脚本会自动读取环境内所有已安装包的兼容性信息
  3. 若部分包未声明Python版本要求,脚本会默认其兼容所有版本,这类包建议你后续手动确认兼容性
  4. 如果后续有新的Python版本发布,直接在python_version_candidates列表中添加对应版本号即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:38:37