简体   繁体   English

尝试使用 powershell 脚本安装最新的 python3 版本

[英]Trying to Install latest python3 version using powershell script

I am currently installing python3 by hardcoding the version in my script.我目前正在通过对脚本中的版本进行硬编码来安装 python3。 I am trying to figure out what I can do to always install the latest stable version of python on the windows agent.我试图弄清楚我能做些什么来始终在 windows 代理上安装最新的稳定版本 python。

$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?以上是我目前正在做的事情,虽然这工作正常,但是我不能对版本进行硬编码并安装最新的稳定 python 版本吗?

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:注意:如果您使用的是最新版本的 Windows 10 或者您使用的是 Windows 11,请考虑使用winget.exe安装 Python,自动针对最新版本:

winget install python --accept-package-agreements

Otherwise , you'll have to resort to web scraping, which is inherently brittle , however (web pages can change).否则,您将不得不求助于web 抓取,但它本质上是脆弱的(网页可以更改)。

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:一种实用的方法是刮https://www.python.org/downloads/进行第一次下载 URL 以.exe结尾,假设指向最新的稳定版本:

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:一个相对更健壮但更麻烦的方法是刮https://www.python.org/ftp/python/代替:

  • Since the version numbers listed there also include prerelease versions, additional checks are required to find the latest stable version.由于此处列出的版本号还包括预发布版本,因此需要进行额外检查才能找到最新的稳定版本。
  • This answer shows a Unix -focused implementation using a sh ( bash ) shell script.这个答案显示了一个Unix使用sh ( bash ) shell 脚本的重点实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM