Last active
April 7, 2026 02:47
-
-
Save rise-worlds/05eb678c3f9ac3d39732b423496ba9a9 to your computer and use it in GitHub Desktop.
check python env
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Get-PythonPath($version) { | |
| $regPath = "HKCU:\SOFTWARE\Python\PythonCore\$version\InstallPath" | |
| try { | |
| $installPath = ((Get-ItemProperty -Path $regPath) | Get-ItemProperty | Select-Object -ExpandProperty "(default)") | |
| if (-not [String]::IsNullOrEmpty($installPath)) { | |
| $regPath = "HKLM:\SOFTWARE\Python\PythonCore\$version\InstallPath" | |
| $installPath = ((Get-ItemProperty -Path $regPath) | Get-ItemProperty | Select-Object -ExpandProperty "(default)") | |
| } | |
| if (-not [String]::IsNullOrEmpty($installPath)) { | |
| return $installPath | |
| } | |
| # Check if Python is available in the current command line path | |
| $pythonVersion = & python -V 2>&1 | |
| if ($pythonVersion -match "Python (\d+\.\d+)" -and $matches[1] -like "$version*") { | |
| $pythonPath = (Get-Command python).Source | |
| $installPath = [System.IO.Path]::GetDirectoryName($pythonPath) | |
| return $installPath | |
| } | |
| } | |
| catch { | |
| } | |
| return $null | |
| } | |
| function Test-Package($name) { | |
| $tempFile = New-TemporaryFile | |
| Start-Process -FilePath pip -ArgumentList "show", $name -NoNewWindow -Wait -RedirectStandardOutput $tempFile | |
| $versionLine = Get-Content $tempFile | Where-Object { $_ -like '*Version:*' } | |
| Remove-Item $tempFile | |
| if ($versionLine) { | |
| $arr = $versionLine -split ':' | |
| if ($arr.Length -gt 1) { | |
| $version = $arr[1].Trim() | |
| # Write-Host "$name 版本号为:$version" | |
| return $version | |
| } | |
| } | |
| return $null | |
| } | |
| if (Test-Path .\.conda) { | |
| $local_path = Join-Path -Path (Get-Location).Path -ChildPath ".conda" | |
| $env:Path = "$local_path;$local_path/Scripts;$env:Path;" | |
| } elseif (Test-Path .\.venv) { | |
| $local_path = Join-Path -Path (Get-Location).Path -ChildPath ".venv" | |
| $env:Path = "$local_path;$local_path/Scripts;$env:Path;" | |
| } elseif (Test-Path .\venv) { | |
| $local_path = Join-Path -Path (Get-Location).Path -ChildPath "venv" | |
| $env:Path = "$local_path;$local_path/Scripts;$env:Path;" | |
| } else { | |
| $python3Path = Get-PythonPath("3.*") | |
| if ($python3Path) { | |
| "Python 3 安装路径为:$python3Path" | |
| $env:Path = "$python3Path;$python3Path/bin;$python3Path/Scripts;$env:Path;" | |
| } else { | |
| "未找到 Python 3 安装路径。" | |
| } | |
| } | |
| if (-not (Test-Package "requests")) { | |
| Start-Process -FilePath pip -ArgumentList "install", "requests" -NoNewWindow -Wait | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment