I am trying to automate the setup of Python environments on Windows and encountered a challenge with legacy Python versions. Specifically, I need a PowerShell script that:
- Detects the last version of
setuptoolsthat is compatible with the currently active local Python version, downloads it, unpacks the archive, and installs it. - Does the same for the latest version of
pipthat supports the active local Python version.
For context, the necessity arises from managing multiple Python environments where each might be using a different Python version, including legacy ones (e.g., Python 2.6). The script must be robust enough to automatically determine which versions of setuptools and pip are compatible with the active Python version and perform the installation process without manual intervention.
I have found various approaches for downloading and installing specific versions of packages, but I am unsure how to dynamically determine the compatible version for the current Python environment.
Has anyone tackled a similar problem, or could you provide insights into how this could be achieved using PowerShell? Any guidance or examples would be greatly appreciated.
P.S. Here is how I think we can achieve a solution:
- fetch the local version of Python using
$pythonVersion = python --version 2>&1 | ForEach-Object { $_ -replace '^Python\s', '' }
- Define a function to query compatible package versions using the PyPI API for the package. Iterate over the releases to find the highest version number that requires a Python version less than or equal to the current Python version. for example:
function Get-CompatibleVersion {
param (
[string]$PackageName,
[string]$PythonVersion
)
$url = "https://pypi.org/pypi/$PackageName/json"
$response = Invoke-RestMethod -Uri $url
$releases = #parsing the JSON format
foreach ($release in $releases) {
$requiresPython = $response.releases.$release[0].requires_python
if (-not $requiresPython) { continue }
$isCompatible = $false
try {
$isCompatible = [System.Version]::Parse($PythonVersion) -le [System.Version]::Parse($requiresPython.Split(',')[0].Trim('<>=').Split(' ')[0])
} catch {}
if ($isCompatible) { return $release }
}
return $null
}
- then getting the latest version of
setuptoolsandpip:
$setuptoolsVersion = Get-CompatibleVersion -PackageName "setuptools" -PythonVersion $pythonVersion
$pipVersion = Get-CompatibleVersion -PackageName "pip" -PythonVersion $pythonVersion