I am currently installing python3 by hardcoding the version in my script. I am trying to figure out what I can do to always install the latest stable version of python on the windows agent.
$url = "https://www.python.org/ftp/python/3.9.10/python-3.9.10.exe"
$pythonPath = "C:/Program Files/python/python-3.9.10.exe"
If ((Test-Path C:) -and !(Test-Path "C:\Program Files\python"))
{
New-Item -Path "C:\Program Files\" -Name "python" -ItemType "directory"
}
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Invoke-WebRequest -Uri $url -OutFile $pythonPath
Above is what I am doing currently, this is working fine though but what can I do not to hardcode the version and install the latest stable python version?
Note: If you're on a recent version of Windows 10 or you're on Windows 11, consider using winget.exe
to install Python, which automatically targets the latest (stable) version:
winget install python --accept-package-agreements
Otherwise , you'll have to resort to web scraping, which is inherently brittle , however (web pages can change).
A pragmatic approach is to scrape https://www.python.org/downloads/
for the first download URL ending in .exe
, which is assumed to point to the latest stable version:
if (
(Invoke-RestMethod 'https://www.python.org/downloads/') -notmatch
'\bhref="(?<url>.+?\.exe)"\s*>\s*Download Python (?<version>\d+\.\d+\.\d+)'
) { throw "Could not determine latest Python version and download URL" }
# The automatic $Matches variable contains the results of the regex-
# matching operation.
$url = $Matches.url
$pythonPath = "C:/Program Files/python/python-$($Matches.version).exe"
# ...
A comparatively more robust, but more cumbersome approach is to scrape https://www.python.org/ftp/python/
instead:
sh
( bash
) shell script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.