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

用PowerShell自动检测安装适配任意Python版本的setuptools与pip

PowerShell脚本自动适配旧版Python安装兼容的setuptools与pip

针对Windows环境下多版本Python管理需求,尤其是旧版Python(如2.6),以下脚本可自动检测当前激活Python环境的兼容版本,完成setuptools和pip的自动安装。

完整实现脚本

<#
.SYNOPSIS
自动为当前激活的Python环境安装兼容的最高版本setuptools和pip
支持旧版Python(如2.6)
#>

# 获取当前Python版本
function Get-PythonVersion {
    try {
        $versionOutput = python --version 2>&1
        if ($LASTEXITCODE -ne 0) { throw "Python命令执行失败" }
        $versionMatch = [regex]::Match($versionOutput, 'Python (\d+\.\d+(?:\.\d+)?)')
        if ($versionMatch.Success) {
            return $versionMatch.Groups[1].Value
        } else {
            throw "无法解析Python版本"
        }
    } catch {
        Write-Error "获取Python版本失败: $_"
        exit 1
    }
}

# 查询PyPI获取指定包的最高兼容版本
function Get-HighestCompatibleVersion {
    param (
        [Parameter(Mandatory=$true)]
        [string]$PackageName,
        [Parameter(Mandatory=$true)]
        [string]$PythonVersion
    )

    try {
        $pypiData = Invoke-RestMethod -Uri "https://pypi.org/pypi/$PackageName/json" -ErrorAction Stop
        
        # 按版本号从高到低排序所有发布版本
        $sortedReleases = $pypiData.releases.PSObject.Properties | ForEach-Object {
            [PSCustomObject]@{
                Version = $_.Name
                RequiresPython = $_.Value[0].requires_python
            }
        } | Sort-Object { [version]$_.Version } -Descending

        # 遍历寻找第一个兼容版本
        foreach ($release in $sortedReleases) {
            if (-not $release.RequiresPython) {
                # 无版本约束的旧版包默认兼容
                return $release.Version
            }

            # 解析最低版本要求
            if ($release.RequiresPython -match '^\s*>=?\s*(\d+\.\d+(?:\.\d+)?)') {
                $minVersion = $matches[1]
                if ([version]$PythonVersion -ge [version]$minVersion) {
                    # 解析版本上限约束(如<3)
                    if ($release.RequiresPython -match '<\s*(\d+\.\d+)') {
                        $maxVersion = $matches[1]
                        if ([version]$PythonVersion -lt [version]$maxVersion) {
                            return $release.Version
                        }
                    } else {
                        return $release.Version
                    }
                }
            }
        }

        Write-Warning "未找到兼容$PackageName的版本"
        return $null
    } catch {
        Write-Error "查询$PackageName版本失败: $_"
        return $null
    }
}

# 安装指定版本的setuptools
function Install-Setuptools {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Version,
        [Parameter(Mandatory=$true)]
        [string]$PythonVersion
    )

    try {
        $tempDir = Join-Path $env:TEMP "setuptools-install"
        if (-not (Test-Path $tempDir)) { New-Item -ItemType Directory -Path $tempDir | Out-Null }

        if ([version]$PythonVersion -lt [version]"2.7") {
            # Python2.6及以下采用源码包安装
            $sourceUrl = "https://files.pythonhosted.org/packages/source/s/setuptools/setuptools-$Version.zip"
            $zipPath = Join-Path $tempDir "setuptools-$Version.zip"
            
            Invoke-WebRequest -Uri $sourceUrl -OutFile $zipPath -ErrorAction Stop
            Expand-Archive -Path $zipPath -DestinationPath $tempDir -Force
            $setupDir = Join-Path $tempDir "setuptools-$Version"
            
            python "$setupDir\setup.py" install
        } else {
            # 较新版本直接用pip安装
            python -m pip install "setuptools==$Version" --upgrade
        }

        Write-Host "setuptools $Version 安装完成"
        Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
    } catch {
        Write-Error "安装setuptools失败: $_"
        exit 1
    }
}

# 安装指定版本的pip
function Install-Pip {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Version,
        [Parameter(Mandatory=$true)]
        [string]$PythonVersion
    )

    try {
        $tempDir = Join-Path $env:TEMP "pip-install"
        if (-not (Test-Path $tempDir)) { New-Item -ItemType Directory -Path $tempDir | Out-Null }

        if ([version]$PythonVersion -lt [version]"2.7") {
            # Python2.6采用源码包安装
            $sourceUrl = "https://files.pythonhosted.org/packages/source/p/pip/pip-$Version.tar.gz"
            $tarPath = Join-Path $tempDir "pip-$Version.tar.gz"
            
            Invoke-WebRequest -Uri $sourceUrl -OutFile $tarPath -ErrorAction Stop
            tar -xzf $tarPath -C $tempDir
            $setupDir = Join-Path $tempDir "pip-$Version"
            
            python "$setupDir\setup.py" install
        } else {
            python -m pip install "pip==$Version" --upgrade
        }

        Write-Host "pip $Version 安装完成"
        Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
    } catch {
        Write-Error "安装pip失败: $_"
        exit 1
    }
}

# 主执行流程
$pythonVersion = Get-PythonVersion
Write-Host "检测到Python版本: $pythonVersion"

$setuptoolsVersion = Get-HighestCompatibleVersion -PackageName "setuptools" -PythonVersion $pythonVersion
if ($setuptoolsVersion) {
    Write-Host "找到兼容的setuptools最高版本: $setuptoolsVersion"
    Install-Setuptools -Version $setuptoolsVersion -PythonVersion $pythonVersion
} else {
    Write-Error "未找到兼容的setuptools版本"
    exit 1
}

$pipVersion = Get-HighestCompatibleVersion -PackageName "pip" -PythonVersion $pythonVersion
if ($pipVersion) {
    Write-Host "找到兼容的pip最高版本: $pipVersion"
    Install-Pip -Version $pipVersion -PythonVersion $pythonVersion
} else {
    Write-Error "未找到兼容的pip版本"
    exit 1
}

Write-Host "所有组件安装完成"

关键逻辑说明

版本检测

  • 增加错误处理,避免Python命令未找到或版本输出异常的情况
  • 使用正则精准提取x.y.z格式的版本号,确保后续比较准确

兼容版本查询

  • 从PyPI拉取包的完整版本列表,按版本号从高到低排序
  • 解析requires_python字段的约束规则,同时兼容无约束的旧版包
  • 严格对比Python版本与包的版本要求,确保返回最高兼容版本

适配旧版Python安装

  • 针对Python2.6及以下版本,采用源码解压后执行setup.py install的方式(旧版Python不支持wheel包,且初始环境无pip)
  • 较新版本Python直接使用pip完成安装,提升效率

注意事项

  • 需使用PowerShell 5.1及以上版本(支持Expand-Archive和Invoke-RestMethod)
  • 多版本Python环境下,需确保当前终端已激活目标Python环境(或指定Python完整路径)
  • Python2.6环境需系统支持tar命令解压tar.gz包,可替换为下载zip格式的pip源码包

内容的提问来源于stack exchange,提问作者Foad S. Farimani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:14:54