Windows 10/11 上 Pyenv-win 完整安装教程

Windows 10/11 上 Pyenv-win 完整安装教程


前言

在 Windows 上开发 Python 项目时,经常会遇到不同项目需要不同 Python 版本的问题(比如项目A用 3.10,项目B用 3.12)。

pyenv-win 是 Windows 平台最稳定的 Python 版本管理工具,可以实现:

  • 一台电脑同时安装多个 Python 版本
  • 全局/目录/终端自由切换版本
  • 不污染系统环境,与 conda 互不冲突

本文记录完整安装流程、踩坑实录、脚本修改、常用命令,新手可直接照做。


一、安装前准备

  1. 卸载/清理旧版 Python、conda 干扰

  2. 关闭所有终端,打开全新 PowerShell

  3. 允许运行脚本(解决权限报错)

    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser


二、自定义路径安装(亲测)

1. 先彻底卸载旧版
bash 复制代码
# 删除安装目录
Remove-Item -Recurse -Force $HOME.pyenv

并删除系统环境变量中的 PYENV/PYENV_ROOT 相关配置。

2. 使用修改后的安装脚本(安装到 S 盘)

将以下代码保存为 install-pyenv-win.ps1

bash 复制代码
<#
    .SYNOPSIS
    Installs pyenv-win

    .DESCRIPTION
    Installs pyenv-win to $HOME\.pyenv
    If pyenv-win is already installed, try to update to the latest version.

    .PARAMETER Uninstall
    Uninstall pyenv-win. Note that this uninstalls any Python versions that were installed with pyenv-win.

    .INPUTS
    None.

    .OUTPUTS
    None.

    .EXAMPLE
    PS> install-pyenv-win.ps1

    .LINK
    Online version: https://pyenv-win.github.io/pyenv-win/
#>
    
param (
    [Switch] $Uninstall = $False
)
    
$PyEnvDir = "D:\env\pyenv"
$PyEnvWinDir = "${PyEnvDir}\pyenv-win"
$BinPath = "${PyEnvWinDir}\bin"
$ShimsPath = "${PyEnvWinDir}\shims"
    
Function Remove-PyEnvVars() {
    $PathParts = [System.Environment]::GetEnvironmentVariable('PATH', "User") -Split ";"
    $NewPathParts = $PathParts.Where{ $_ -ne $BinPath }.Where{ $_ -ne $ShimsPath }
    $NewPath = $NewPathParts -Join ";"
    [System.Environment]::SetEnvironmentVariable('PATH', $NewPath, "User")

    [System.Environment]::SetEnvironmentVariable('PYENV', $null, "User")
    [System.Environment]::SetEnvironmentVariable('PYENV_ROOT', $null, "User")
    [System.Environment]::SetEnvironmentVariable('PYENV_HOME', $null, "User")
}

Function Remove-PyEnv() {
    Write-Host "Removing $PyEnvDir..."
    If (Test-Path $PyEnvDir) {
        Remove-Item -Path $PyEnvDir -Recurse
    }
    Write-Host "Removing environment variables..."
    Remove-PyEnvVars
}

Function Get-CurrentVersion() {
    $VersionFilePath = "$PyEnvDir\.version"
    If (Test-Path $VersionFilePath) {
        $CurrentVersion = Get-Content $VersionFilePath
    }
    Else {
        $CurrentVersion = ""
    }

    Return $CurrentVersion
}

Function Get-LatestVersion() {
    $LatestVersionFilePath = "$PyEnvDir\latest.version"
    (New-Object System.Net.WebClient).DownloadFile("https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/.version", $LatestVersionFilePath)
    $LatestVersion = Get-Content $LatestVersionFilePath

    Remove-Item -Path $LatestVersionFilePath

    Return $LatestVersion
}

Function Main() {
    If ($Uninstall) {
        Remove-PyEnv
        If ($? -eq $True) {
            Write-Host "pyenv-win successfully uninstalled."
        }
        Else {
            Write-Host "Uninstallation failed."
        }
        exit
    }

    $BackupDir = "${env:Temp}/pyenv-win-backup"
    
    $CurrentVersion = Get-CurrentVersion
    If ($CurrentVersion) {
        Write-Host "pyenv-win $CurrentVersion installed."
        $LatestVersion = Get-LatestVersion
        If ($CurrentVersion -eq $LatestVersion) {
            Write-Host "No updates available."
            exit
        }
        Else {
            Write-Host "New version available: $LatestVersion. Updating..."
            
            Write-Host "Backing up existing Python installations..."
            $FoldersToBackup = "install_cache", "versions", "shims"
            ForEach ($Dir in $FoldersToBackup) {
                If (-not (Test-Path $BackupDir)) {
                    New-Item -ItemType Directory -Path $BackupDir
                }
                Move-Item -Path "${PyEnvWinDir}/${Dir}" -Destination $BackupDir
            }
            
            Write-Host "Removing $PyEnvDir..."
            Remove-Item -Path $PyEnvDir -Recurse
        }   
    }

    New-Item -Path $PyEnvDir -ItemType Directory

    $DownloadPath = "$PyEnvDir\pyenv-win.zip"

    (New-Object System.Net.WebClient).DownloadFile("https://github.com/pyenv-win/pyenv-win/archive/master.zip", $DownloadPath)

    Start-Process -FilePath "powershell.exe" -ArgumentList @(
        "-NoProfile",
        "-Command `"Microsoft.PowerShell.Archive\Expand-Archive -Path \`"$DownloadPath\`" -DestinationPath \`"$PyEnvDir\`"`""
    ) -NoNewWindow -Wait

    Move-Item -Path "$PyEnvDir\pyenv-win-master\*" -Destination "$PyEnvDir"
    Remove-Item -Path "$PyEnvDir\pyenv-win-master" -Recurse
    Remove-Item -Path $DownloadPath

    # Update env vars
    [System.Environment]::SetEnvironmentVariable('PYENV', "${PyEnvWinDir}\", "User")
    [System.Environment]::SetEnvironmentVariable('PYENV_ROOT', "${PyEnvWinDir}\", "User")
    [System.Environment]::SetEnvironmentVariable('PYENV_HOME', "${PyEnvWinDir}\", "User")

    $PathParts = [System.Environment]::GetEnvironmentVariable('PATH', "User") -Split ";"

    # Remove existing paths, so we don't add duplicates
    $NewPathParts = $PathParts.Where{ $_ -ne $BinPath }.Where{ $_ -ne $ShimsPath }
    $NewPathParts = ($BinPath, $ShimsPath) + $NewPathParts
    $NewPath = $NewPathParts -Join ";"
    [System.Environment]::SetEnvironmentVariable('PATH', $NewPath, "User")

    If (Test-Path $BackupDir) {
        Write-Host "Restoring Python installations..."
        Move-Item -Path "$BackupDir/*" -Destination $PyEnvWinDir
    }
    
    If ($? -eq $True) {
        Write-Host "pyenv-win is successfully installed. You may need to close and reopen your terminal before using it."
    }
    Else {
        Write-Host "pyenv-win was not installed successfully. If this issue persists, please open a ticket: https://github.com/pyenv-win/pyenv-win/issues."
    }
}

Main
3. 运行脚本
bash 复制代码
D:\env\pyenv 为pyenv安装的路径
复制代码
.\install-pyenv-win.ps1
4. 验证安装
css 复制代码
pyenv --version

出现版本号即成功。


三、pyenv-win 常用基本命令(全终端通用)

1. 查看信息
bash 复制代码
pyenv --version             # 查看 pyenv 版本
pyenv versions              # 查看已安装的 Python
pyenv install --list        # 查看可安装版本
pyenv which python          # 查看当前 Python 路径
2. 安装/卸载 Python
bash 复制代码
pyenv install 3.12.2        # 安装 Python 3.12.2
pyenv uninstall 3.10.0      # 卸载版本
pyenv rehash                # 刷新环境(安装后自动执行)
3. 切换版本(最重要)
bash 复制代码
pyenv global 3.12.2         # 全局默认版本
pyenv local 3.11.9          # 当前目录专用版本
pyenv shell 3.10.14         # 当前终端临时版本
pyenv local --unset         # 取消目录版本
4. 验证版本
css 复制代码
python --version
pip --version

四、常见问题汇总

1. pyenv root 报错

原因:Windows 版不支持此命令

替代:

bash 复制代码
$env:PYENV_ROOT
pyenv which python
2. 安装 Python 慢/失败

解决:开启代理,或手动下载安装包放入:

ini 复制代码
安装路径的install_cache下
python各个版本下载地址:https://registry.npmmirror.com/binary.html?path=python

基于链接:juejin.cn/post/762437...

相关推荐
想会飞的蒲公英1 小时前
PyTorch中SGD 与 Momentum 从零理解:给最朴素的优化器加上“惯性“
人工智能·pytorch·python·深度学习·机器学习
拿铁铁1 小时前
平板坡口机换碳刷时间参考手册
python·电脑
略略略咯咯2 小时前
stream流浅拷贝
开发语言·python
vx-程序开发2 小时前
【java项目分享】springboot农产品销售平台14952
java·javascript·spring boot·python·eclipse·django·php
Wesleyblue2 小时前
python计算余弦相似性和汉明距离
python·余弦相似性·汉明距离·二进制编码·数值向量
Patrick在香港2 小时前
Python依赖管理从踩坑到选型:pip/poetry/uv四种方案全面实测
开发语言·python·数据分析·scikit-learn·ai编程·pip·uv
circuitsosk3 小时前
知识问答领域大语言模型设计:对标豆包与DeepSeek的工程实践
人工智能·python·语言模型·自然语言处理·llm·豆包·deepseek
卷无止境3 小时前
从源码到货架:拆解 Python 打包发布的核心逻辑
后端·python
这就是佬们吗3 小时前
企业Agent落地为什么需要RAG?
人工智能·python·fastapi