Repository navigation
Expand file tree
/
Copy pathPython-Installer.bat
More file actions
693 lines (616 loc) · 30.6 KB
/
Copy pathPython-Installer.bat
File metadata and controls
693 lines (616 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
@ECHO OFF
SETLOCAL EnableExtensions
TITLE Python Latest Installer
REM ============================================================
REM Python Latest Installer
REM
REM Usage:
REM install_python.bat [3.xx] [options]
REM
REM 3.xx pin to the newest release of that series, e.g. 3.13
REM /allusers install for all users (needs admin, asks for UAC)
REM /junction create or refresh the stable Python3 folder link
REM /nojunction do not create the stable folder link
REM /unattended no prompts and no final pause
REM (the junction defaults to ON, see JunctionDefault)
REM /arch=NAME amd64, arm64 or x86 (default: native)
REM /? show this help
REM
REM Set NOPAUSE=1 beforehand to skip the final PAUSE as well.
REM
REM The real work is done by the PowerShell block at the bottom
REM of this file. cmd.exe never reads past the EXIT /B below.
REM ============================================================
SET "PY_ARGS=%*"
SET "PY_BATCH=%~f0"
SET "PY_RESULT_FILE=%TEMP%\py_installer_result_%RANDOM%%RANDOM%.txt"
DEL /Q "%PY_RESULT_FILE%*" >NUL 2>&1
REM Prefer the native 64-bit PowerShell even when started from a 32-bit cmd.
SET "PS_EXE=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
IF DEFINED PROCESSOR_ARCHITEW6432 IF EXIST "%SystemRoot%\Sysnative\WindowsPowerShell\v1.0\powershell.exe" SET "PS_EXE=%SystemRoot%\Sysnative\WindowsPowerShell\v1.0\powershell.exe"
IF NOT EXIST "%PS_EXE%" SET "PS_EXE=powershell"
"%PS_EXE%" -NoProfile -ExecutionPolicy Bypass -Command "& ([scriptblock]::Create(([regex]::Split([IO.File]::ReadAllText('%~f0'),'(?m)^:::PS_BEGIN\s*$')[1])))"
SET "RC=%ERRORLEVEL%"
IF EXIST "%PY_RESULT_FILE%.nopause" SET "NOPAUSE=1"
IF EXIST "%PY_RESULT_FILE%.skip" GOTO :SKIPPED
IF "%RC%"=="0" GOTO :AFTER_PS
IF "%RC%"=="2" GOTO :AFTER_PS
ECHO.
ECHO Installation did not complete. Exit code: %RC%
DEL /Q "%PY_RESULT_FILE%*" >NUL 2>&1
IF NOT DEFINED NOPAUSE PAUSE
EXIT /B %RC%
:SKIPPED
DEL /Q "%PY_RESULT_FILE%*" >NUL 2>&1
IF NOT DEFINED NOPAUSE PAUSE
EXIT /B %RC%
:AFTER_PS
SET "PYEXE="
SET "SESS_ADD="
SET "NOSESS="
IF EXIST "%PY_RESULT_FILE%" SET /P PYEXE=<"%PY_RESULT_FILE%"
IF EXIST "%PY_RESULT_FILE%" FOR /F "usebackq skip=1 delims=" %%L IN ("%PY_RESULT_FILE%") DO SET "SESS_ADD=%%L"
IF EXIST "%PY_RESULT_FILE%.nosession" SET "NOSESS=1"
DEL /Q "%PY_RESULT_FILE%*" >NUL 2>&1
IF DEFINED PYEXE GOTO :HAVE_PY
ECHO [ERROR] The installer finished but did not report a python.exe path.
IF NOT DEFINED NOPAUSE PAUSE
EXIT /B 1
:HAVE_PY
REM Update the current CMD session too, unless PATH is too long for a safe SET.
IF DEFINED NOSESS GOTO :SKIP_SESSION
IF NOT DEFINED SESS_ADD GOTO :SKIP_SESSION
SET "PATH=%SESS_ADD%;%PATH%"
GOTO :CHECK_PY
:SKIP_SESSION
ECHO [INFO] Current window PATH not updated. Open a new terminal.
:CHECK_PY
ECHO.
py -3 --version >NUL 2>&1
IF ERRORLEVEL 1 GOTO :NO_LAUNCHER
ECHO Launcher check passed: py -3 works.
GOTO :DONE
:NO_LAUNCHER
ECHO [WARN] py launcher not found in this window. The python.exe path below still works.
:DONE
ECHO.
IF "%RC%"=="2" ECHO [WARN] Completed with warnings. See the messages above.
IF NOT "%RC%"=="2" ECHO Python installation is complete.
ECHO Python:
ECHO %PYEXE%
ECHO.
ECHO Open a NEW terminal for PATH changes to take effect.
ECHO.
IF NOT DEFINED NOPAUSE PAUSE
EXIT /B %RC%
:::PS_BEGIN
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch {}
# ---- Tunables ----------------------------------------------------------
$JunctionDefault = $true # prompt default, and the behaviour when /unattended is used
$PathHardLimit = 32000 # Windows caps an expanded variable at 32,767 chars; keep headroom
$PathSoftLimit = 2047 # older tools and dialogs choke on longer PATH values
$SessionPathMax = 7500 # cmd.exe lines are limited to 8191 chars
$ResultFile = $env:PY_RESULT_FILE
$Index = 'https://www.python.org/ftp/python/'
# ---- Small helpers -----------------------------------------------------
function Fail([string]$Message, [int]$Code = 1) {
Write-Host "[ERROR] $Message" -ForegroundColor Red
exit $Code
}
function Warn([string]$Message) { Write-Host "[WARN] $Message" -ForegroundColor Yellow }
function Set-Flag([string]$Suffix) { try { Set-Content -LiteralPath ($ResultFile + $Suffix) -Value '1' } catch {} }
function Show-Help {
Write-Host 'Usage: install_python.bat [3.xx] [options]'
Write-Host ' 3.xx pin to the newest release of that series, e.g. 3.13'
Write-Host ' /allusers install for all users (needs admin, asks for UAC)'
Write-Host ' /junction create or refresh the stable Python3 folder link'
Write-Host ' /nojunction do not create the stable folder link'
Write-Host ' /unattended no prompts, no final pause'
Write-Host " (junction defaults to: $JunctionDefault)"
Write-Host ' /arch=NAME amd64, arm64 or x86 (default: native)'
Write-Host ' /? show this help'
}
# ---- Arguments ---------------------------------------------------------
$Series = $null; $ArchOverride = $null
$Unattended = $false; $AllUsers = $false; $Junction = $null
foreach ($raw in @($env:PY_ARGS -split '\s+' | Where-Object { $_ })) {
$tok = $raw.Trim('"')
if ($tok -match '^3\.\d+$') { $Series = $tok; continue }
$a = $tok.TrimStart([char[]]'/-').ToLowerInvariant()
$val = $null
if ($a -match '^([a-z]+)[=:](.+)$') { $a = $Matches[1]; $val = $Matches[2] }
switch -Regex ($a) {
'^(\?|h|help)$' { Show-Help; Set-Flag '.skip'; exit 0 }
'^(unattended|quiet|silent|y)$' { $Unattended = $true }
'^(allusers|machine)$' { $AllUsers = $true }
'^(peruser|currentuser)$' { $AllUsers = $false }
'^(junction|stablepath)$' { $Junction = $true }
'^(nojunction|nostablepath)$' { $Junction = $false }
'^series$' { $Series = $val }
'^arch$' { $ArchOverride = $val }
default { Fail "Unknown argument: $raw (use /? for help)" }
}
}
if ($Unattended) { Set-Flag '.nopause' }
if ($Series -and $Series -notmatch '^3\.\d+$') { Fail "Series must look like 3.13 (got '$Series')." }
# ---- Environment guards ------------------------------------------------
$os = [Environment]::OSVersion.Version
$pinnedOld = $false
if ($Series) { $pinnedOld = ([int]($Series.Split('.')[1]) -le 8) }
if ($os.Major -lt 10 -and -not $pinnedOld) {
Fail 'Current Python releases need Windows 10 or newer. Pin an older series (e.g. 3.8) if you must.'
}
if ($os.Major -ge 10 -and $os.Build -lt 17763) {
Warn "Windows build $($os.Build) is old (older than 1809). Recent Python releases may refuse to install or run."
}
$sMode = $false
try {
$sku = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' -Name 'SkuPolicyRequired' -ErrorAction Stop
if ($sku.SkuPolicyRequired -eq 1) { $sMode = $true }
} catch {}
if ($sMode) {
Fail 'This Windows is in S mode (or a similar locked-down edition) and only runs Store apps. Install Python from the Microsoft Store instead.'
}
$osArch = ''
try { $osArch = [string][Runtime.InteropServices.RuntimeInformation]::OSArchitecture } catch {}
if (-not $osArch) {
$osArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
}
$nativeArch = $null
switch -Regex ($osArch) {
'^(x64|amd64)$' { $nativeArch = 'amd64' }
'^arm64$' { $nativeArch = 'arm64' }
'^x86$' { $nativeArch = 'x86' }
'^arm$' { Fail 'Windows RT / 32-bit ARM is not supported: python.org ships no installer for it.' }
default { Fail "Unsupported processor architecture: $osArch" }
}
$Arch = $nativeArch
if ($ArchOverride) {
switch ($ArchOverride.ToLowerInvariant()) {
'amd64' { $Arch = 'amd64' }
'x64' { $Arch = 'amd64' }
'arm64' { $Arch = 'arm64' }
'x86' { $Arch = 'x86' }
'win32' { $Arch = 'x86' }
default { Fail "Unknown arch '$ArchOverride' (use amd64, arm64 or x86)." }
}
}
if ($Arch -eq 'arm64' -and $nativeArch -ne 'arm64') { Fail 'The ARM64 build only runs on ARM64 Windows.' }
if ($Arch -eq 'amd64' -and $nativeArch -eq 'x86') { Fail '64-bit Python cannot run on 32-bit Windows.' }
if ($Arch -eq 'amd64' -and $nativeArch -eq 'arm64') { Warn 'x64 Python on ARM64 runs under emulation (needs Windows 11).' }
$suffix = @{ amd64 = '-amd64'; arm64 = '-arm64'; x86 = '' }[$Arch]
$platTag = @{ amd64 = 'win-amd64'; arm64 = 'win-arm64'; x86 = 'win32' }[$Arch]
# ---- Elevation (all-users only) ---------------------------------------
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$Interactive = (-not $Unattended) -and [Environment]::UserInteractive -and (-not [Console]::IsInputRedirected)
if ($AllUsers -and -not $isAdmin) {
if (-not $Interactive) { Fail 'An all-users install needs an elevated (Administrator) prompt.' 5 }
Write-Host 'An all-users install needs administrator rights. Requesting elevation...'
$argLine = '/c ""' + $env:PY_BATCH + '" ' + $env:PY_ARGS + '"'
$child = Start-Process -FilePath $env:ComSpec -ArgumentList $argLine -Verb RunAs -Wait -PassThru
Write-Host 'The installer ran in the elevated window. Open a new terminal to use the updated PATH.'
Set-Flag '.skip'
exit $child.ExitCode
}
# ---- Locations ---------------------------------------------------------
$UserRoot = Join-Path $env:LOCALAPPDATA 'Programs\Python'
$MachRoot = if ($Arch -eq 'x86' -and ${env:ProgramFiles(x86)}) { ${env:ProgramFiles(x86)} } else { $env:ProgramFiles }
$InstallBase = if ($AllUsers) { $MachRoot } else { $UserRoot }
$Stable = Join-Path $InstallBase 'Python3'
# ---- Python discovery --------------------------------------------------
function Get-PyInfo([string]$Exe) {
try {
$out = & $Exe -c "import sys, sysconfig; print('.'.join(map(str, sys.version_info[:3])), sysconfig.get_platform())" 2>$null
if ($LASTEXITCODE -eq 0 -and "$out" -match '^(\d+\.\d+\.\d+)\s+(\S+)$') {
return [pscustomobject]@{ Version = [version]$Matches[1]; Platform = $Matches[2] }
}
} catch {}
return $null
}
function Test-Reparse([string]$Path) {
$i = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
return [bool]($i -and ($i.Attributes -band [IO.FileAttributes]::ReparsePoint))
}
function Get-InstalledPythons {
$found = @{}
# Registry (PEP 514) is the most reliable source, whatever the folder is called.
$reg = @(
@{ Path = 'HKCU:\Software\Python\PythonCore'; Scope = 'user' },
@{ Path = 'HKLM:\Software\Python\PythonCore'; Scope = 'machine' },
@{ Path = 'HKLM:\Software\WOW6432Node\Python\PythonCore'; Scope = 'machine' }
)
foreach ($r in $reg) {
if (-not (Test-Path $r.Path)) { continue }
foreach ($tag in (Get-ChildItem $r.Path -ErrorAction SilentlyContinue)) {
try {
$ip = Get-ItemProperty -Path (Join-Path $tag.PSPath 'InstallPath') -ErrorAction Stop
$exe = $null
if ($ip.ExecutablePath) { $exe = [string]$ip.ExecutablePath }
elseif ($ip.'(default)') { $exe = Join-Path ([string]$ip.'(default)') 'python.exe' }
if ($exe -and -not $found.ContainsKey($exe)) { $found[$exe] = $r.Scope }
} catch {}
}
}
# Folder scan as a fallback. Junctions are skipped so the stable link
# is never mistaken for a real install.
$dirs = @(
@{ Path = $UserRoot; Scope = 'user' },
@{ Path = $env:ProgramFiles; Scope = 'machine' },
@{ Path = ${env:ProgramFiles(x86)}; Scope = 'machine' }
)
foreach ($d in $dirs) {
if (-not $d.Path) { continue }
Get-ChildItem -Path $d.Path -Directory -Filter 'Python3*' -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
$exe = Join-Path $_.FullName 'python.exe'
if (-not $found.ContainsKey($exe)) { $found[$exe] = $d.Scope }
}
}
foreach ($exe in @($found.Keys)) {
if (-not (Test-Path -LiteralPath $exe)) { continue }
$info = Get-PyInfo $exe
if ($info -and $info.Version.Major -eq 3) {
[pscustomobject]@{ Path = $exe; Version = $info.Version; Platform = $info.Platform; Scope = $found[$exe] }
}
}
}
# Newest STABLE release that actually has an installer for this architecture.
# Security-only and not-yet-final releases have none, so they are skipped by
# probing the real file instead of trusting a version string.
function Get-LatestInstallable {
$versions = @()
try {
$html = (Invoke-WebRequest -Uri $Index -UseBasicParsing -TimeoutSec 30).Content
$versions = @([regex]::Matches($html, 'href="(\d+\.\d+\.\d+)/"') | ForEach-Object { [version]$_.Groups[1].Value })
} catch {
Write-Host " (ftp index unavailable: $($_.Exception.Message))"
}
if ($versions.Count -eq 0) {
try {
$html = (Invoke-WebRequest -Uri 'https://www.python.org/downloads/windows/' -UseBasicParsing -TimeoutSec 30).Content
$versions = @([regex]::Matches($html, 'Python (3\.\d+\.\d+)') | ForEach-Object { [version]$_.Groups[1].Value })
} catch {
Write-Host " (downloads page unavailable: $($_.Exception.Message))"
}
}
$versions = @($versions | Where-Object { $_.Major -eq 3 } | Sort-Object -Unique -Descending)
if ($Series) {
$versions = @($versions | Where-Object { ('{0}.{1}' -f $_.Major, $_.Minor) -eq $Series })
}
$tried = 0
foreach ($v in $versions) {
if ($tried++ -ge 25) { break }
$url = "$Index$v/python-$v$suffix.exe"
try {
$r = Invoke-WebRequest -Uri $url -Method Head -UseBasicParsing -TimeoutSec 30
if ($r.StatusCode -eq 200) { return [pscustomobject]@{ Version = $v; Url = $url } }
} catch {}
}
return $null
}
# ---- Stable-path junction ---------------------------------------------
function Ask-YesNo([string]$Question, [bool]$Default) {
$yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Yes'
$no = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'No'
$def = if ($Default) { 0 } else { 1 }
return ($Host.UI.PromptForChoice('Stable path', $Question, @($yes, $no), $def) -eq 0)
}
# Returns created, updated, unchanged or realdir (a real folder is in the way).
function Set-StableJunction([string]$Link, [string]$Target) {
$result = 'created'
if (Test-Path -LiteralPath $Link) {
if (-not (Test-Reparse $Link)) { return 'realdir' }
$cur = (Get-Item -LiteralPath $Link -Force).Target
if ($cur -and ([string]@($cur)[0]).TrimEnd('\') -eq $Target.TrimEnd('\')) { return 'unchanged' }
[IO.Directory]::Delete($Link) # removes only the link, never the target
$result = 'updated'
}
[void](New-Item -ItemType Junction -Path $Link -Value $Target)
return $result
}
# ---- PATH handling -----------------------------------------------------
function Get-PathKey([bool]$Machine, [bool]$Writable) {
try {
if ($Machine) {
return [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $Writable)
}
return [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $Writable)
} catch { return $null }
}
function Read-RawPath($Key) {
if ($null -eq $Key) { return '' }
return [string]$Key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
}
function Expand-Len([string]$s) { return [Environment]::ExpandEnvironmentVariables($s).Length }
function Norm([string]$e) {
return [Environment]::ExpandEnvironmentVariables($e.Trim().Trim('"')).TrimEnd('\').ToLowerInvariant()
}
# Replace a leading expanded prefix with a %VAR% only when that is shorter.
function Compact-Entry([string]$Entry, [bool]$Machine) {
$e = $Entry.Trim()
if ($e.Contains('%')) { return $e }
$names = @('ProgramFiles', 'ProgramFiles(x86)', 'ProgramData', 'SystemRoot')
if (-not $Machine) { $names = @('LOCALAPPDATA', 'APPDATA', 'USERPROFILE') + $names }
$best = $null
foreach ($n in $names) {
$val = [Environment]::GetEnvironmentVariable($n)
if (-not $val) { continue }
$val = $val.TrimEnd('\')
$isMatch = $e.Equals($val, [StringComparison]::OrdinalIgnoreCase) -or $e.StartsWith($val + '\', [StringComparison]::OrdinalIgnoreCase)
if ($isMatch -and (('%' + $n + '%').Length -lt $val.Length)) {
if (-not $best -or $val.Length -gt $best.Value.Length) { $best = [pscustomobject]@{ Name = $n; Value = $val } }
}
}
if ($best) { return ('%' + $best.Name + '%' + $e.Substring($best.Value.Length)) }
return $e
}
# De-duplicate (first occurrence wins). Optionally compact, optionally drop
# entries whose LOCAL folder does not exist (never UNC, never unresolved %VAR%).
function Optimize-Entries([string[]]$Entries, [bool]$Machine, [bool]$Compact, [bool]$DropMissing, [string[]]$Protect) {
$seen = @{}
$out = New-Object System.Collections.Generic.List[string]
foreach ($e in $Entries) {
$x = $e.Trim()
if (-not $x) { continue }
$k = Norm $x
if ($seen.ContainsKey($k)) { continue }
if ($DropMissing -and ($Protect -notcontains $k) -and -not $k.StartsWith('\\') -and -not $k.Contains('%')) {
if (-not (Test-Path -LiteralPath $k)) { continue }
}
$seen[$k] = $true
if ($Compact) { $out.Add((Compact-Entry $x $Machine)) } else { $out.Add($x) }
}
return $out.ToArray()
}
function Backup-Path {
try {
$dir = Join-Path $env:LOCALAPPDATA 'PythonInstaller'
[void](New-Item -ItemType Directory -Force -Path $dir)
$file = Join-Path $dir ('path-backup-{0}.txt' -f (Get-Date -Format 'yyyyMMdd-HHmmss'))
$u = Get-PathKey $false $false
$m = Get-PathKey $true $false
$lines = @('[User Path]', (Read-RawPath $u), '', '[Machine Path]', (Read-RawPath $m))
if ($u) { $u.Close() }
if ($m) { $m.Close() }
Set-Content -LiteralPath $file -Value $lines -Encoding UTF8
Write-Host " PATH backup: $file"
} catch {
Warn "Could not write a PATH backup: $($_.Exception.Message)"
}
}
# Returns updated, unchanged, toolong or failed.
function Update-Path([bool]$Machine, [string[]]$Add, [string]$Base) {
$scopeName = if ($Machine) { 'System' } else { 'User' }
$key = Get-PathKey $Machine $true
$other = Get-PathKey (-not $Machine) $false
if (-not $key) {
Warn "Could not open the $scopeName PATH registry key for writing."
return 'failed'
}
try {
$current = Read-RawPath $key
$otherLen = Expand-Len (Read-RawPath $other)
# Drop stale Python folders of ours; our new entries go first.
$stale = '^' + [regex]::Escape($Base.TrimEnd('\')) + '\\Python3\d*(\\Scripts)?$'
$entries = @($Add)
foreach ($e in ($current -split ';')) {
if ([string]::IsNullOrWhiteSpace($e)) { continue }
if ((Norm $e) -match $stale) { continue }
$entries += $e.Trim()
}
$addKeys = @($Add | ForEach-Object { Norm $_ })
# Tier 1: plain de-duplication (semantics-preserving).
$new = (@(Optimize-Entries $entries $Machine $false $false $addKeys)) -join ';'
# Tier 2: over the legacy limit, shorten with %VAR% forms if that helps.
if ($new.Length -gt $PathSoftLimit) {
$short = (@(Optimize-Entries $entries $Machine $true $false $addKeys)) -join ';'
if ($short.Length -lt $new.Length) {
$new = $short
Write-Host ' Shortened PATH entries with environment variables to save space.'
}
}
# Tier 3: over the real limit, drop entries whose local folder is gone.
$total = (Expand-Len $new) + 1 + $otherLen
if ($total -gt $PathHardLimit) {
Warn 'PATH would exceed the safe length. Removing duplicates and entries for missing local folders...'
$new = (@(Optimize-Entries $entries $Machine $true $true $addKeys)) -join ';'
$total = (Expand-Len $new) + 1 + $otherLen
}
if ($total -gt $PathHardLimit) {
Warn "Combined PATH would still be $total characters (safe limit $PathHardLimit). PATH was NOT changed."
return 'toolong'
}
if ($new -ceq $current) {
Write-Host " $scopeName PATH already correct."
return 'unchanged'
}
if ($new.Length -gt $PathSoftLimit) {
Warn "$scopeName PATH is $($new.Length) characters. Some older tools and dialogs cannot handle more than $PathSoftLimit."
}
Backup-Path
$key.SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString)
# Broadcast WM_SETTINGCHANGE so new processes pick the change up.
[Environment]::SetEnvironmentVariable('PYINST_BROADCAST', '1', 'User')
[Environment]::SetEnvironmentVariable('PYINST_BROADCAST', $null, 'User')
Write-Host " $scopeName PATH updated ($($new.Length) characters)."
return 'updated'
} finally {
$key.Close()
if ($other) { $other.Close() }
}
}
# ---- Main --------------------------------------------------------------
try {
Write-Host '=========================================='
Write-Host ' Python Latest Installer'
Write-Host (' Scope: {0} Arch: {1}' -f $(if ($AllUsers) { 'all users' } else { 'current user' }), $Arch)
if ($Series) { Write-Host " Pinned to series: $Series" }
Write-Host '=========================================='
Write-Host ''
# 1) Existing installs (right architecture, right scope)
$installed = @(Get-InstalledPythons | Where-Object { $_.Platform -eq $platTag })
if ($Series) {
$installed = @($installed | Where-Object { ('{0}.{1}' -f $_.Version.Major, $_.Version.Minor) -eq $Series })
}
if ($AllUsers) { $installed = @($installed | Where-Object { $_.Scope -eq 'machine' }) }
$best = $installed | Sort-Object Version -Descending | Select-Object -First 1
if ($best) {
Write-Host 'Found existing Python:'
Write-Host " $($best.Path) (Python $($best.Version), $($best.Scope) install)"
} else {
Write-Host 'No existing Python found.'
}
Write-Host ''
# 2) Stable-path decision, asked up front so you can walk away afterwards
$StableIsRealDir = (Test-Path -LiteralPath $Stable) -and -not (Test-Reparse $Stable)
$WantJunction = $JunctionDefault
if ($null -ne $Junction) {
$WantJunction = $Junction
} elseif ($Interactive -and -not $StableIsRealDir) {
$WantJunction = Ask-YesNo "Keep a stable folder ($Stable) that always points to the newest Python?" $JunctionDefault
Write-Host ''
}
# 3) Latest installable release
Write-Host 'Checking latest Python 3 release on python.org...'
$latest = Get-LatestInstallable
$pyExe = $null
if (-not $latest) {
if ($best) {
Warn 'Could not determine the latest version (offline?). Keeping the existing Python.'
$pyExe = $best.Path
} else {
Fail 'Could not find a downloadable installer on python.org, and no Python is installed.'
}
} else {
Write-Host "Latest installable version: $($latest.Version)"
Write-Host "Download URL: $($latest.Url)"
Write-Host ''
if ($best -and $best.Version -ge $latest.Version) {
Write-Host 'Python is already up to date.'
$pyExe = $best.Path
} else {
# Versioned folder, so a new minor never overwrites an older one.
# Same minor already in our root: upgrade it in place instead.
$TargetDir = Join-Path $InstallBase ('Python{0}{1}' -f $latest.Version.Major, $latest.Version.Minor)
if ($best -and $best.Version.Major -eq $latest.Version.Major -and $best.Version.Minor -eq $latest.Version.Minor) {
$bestDir = Split-Path -Parent $best.Path
if ($bestDir.StartsWith($InstallBase, [StringComparison]::OrdinalIgnoreCase)) { $TargetDir = $bestDir }
}
$installer = Join-Path $env:TEMP ('python-{0}{1}.exe' -f $latest.Version, $suffix)
try {
# 4) Download with retries
Write-Host "Downloading Python $($latest.Version) installer..."
$ok = $false
for ($i = 1; $i -le 3 -and -not $ok; $i++) {
try {
Invoke-WebRequest -Uri $latest.Url -OutFile $installer -UseBasicParsing
if ((Get-Item -LiteralPath $installer).Length -gt 1MB) { $ok = $true }
else { Write-Host " attempt $i produced a suspiciously small file." }
} catch {
Write-Host " attempt $i failed: $($_.Exception.Message)"
}
if (-not $ok -and $i -lt 3) { Start-Sleep -Seconds 3 }
}
if (-not $ok) { Fail 'Installer download failed.' }
# 5) Signature must belong to the Python Software Foundation
$sig = Get-AuthenticodeSignature -FilePath $installer
$subject = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { '' }
if ($subject -notmatch 'Python Software Foundation') {
Fail "Installer is not signed by the Python Software Foundation (signer: '$subject')."
}
if ($sig.Status -ne 'Valid') {
Warn "Signature status is '$($sig.Status)' (signer matches PSF). Continuing."
}
# 6) Install
Write-Host ''
Write-Host "Installing Python $($latest.Version) to:"
Write-Host " $TargetDir"
$instArgs = @(
'/quiet', "InstallAllUsers=$([int]$AllUsers)", 'Include_pip=1', 'Include_test=0',
'Include_launcher=1', 'PrependPath=0', 'Shortcuts=0',
"TargetDir=`"$TargetDir`""
)
$p = Start-Process -FilePath $installer -ArgumentList $instArgs -Wait -PassThru
if ($p.ExitCode -eq 1638) {
Warn 'The installer reports a conflicting install of this Python version family'
Warn '(possibly the other scope). Uninstall it first, or use the matching scope.'
} elseif ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) {
Fail "Installer exited with code $($p.ExitCode)." $p.ExitCode
}
$pyExe = Join-Path $TargetDir 'python.exe'
if (-not (Test-Path -LiteralPath $pyExe)) {
Fail "Install finished but python.exe was not found at: $pyExe"
}
} finally {
if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction SilentlyContinue }
}
}
}
$pyDir = Split-Path -Parent $pyExe
# 7) Stable-path junction
$pathDir = $pyDir
if ($WantJunction) {
Write-Host ''
if ($pyDir.TrimEnd('\') -eq $Stable.TrimEnd('\')) {
Write-Host "Python already lives at the stable path: $Stable"
$pathDir = $Stable
} else {
try {
[void](New-Item -ItemType Directory -Force -Path $InstallBase)
$js = Set-StableJunction $Stable $pyDir
if ($js -eq 'realdir') {
Warn "A real folder already exists at $Stable (probably from an older install), so a link cannot go there."
Warn 'Uninstall that Python (Settings > Apps) and run this again to switch to the stable link.'
} elseif (Test-Path -LiteralPath (Join-Path $Stable 'python.exe')) {
Write-Host "Stable path ($js): $Stable -> $pyDir"
$pathDir = $Stable
} else {
Warn "The link at $Stable does not resolve to a Python. Using the real folder."
}
} catch {
Warn "Could not create the stable-path link: $($_.Exception.Message)"
}
}
}
# 8) PATH
Write-Host ''
Write-Host 'Ensuring Python is on your PATH...'
$toAdd = @($pathDir, (Join-Path $pathDir 'Scripts'))
if (-not $AllUsers) {
$launcher = Join-Path $UserRoot 'Launcher'
if (Test-Path -LiteralPath (Join-Path $launcher 'py.exe')) { $toAdd += $launcher }
}
$pathStatus = Update-Path $AllUsers $toAdd $InstallBase
$exitCode = 0
if ($pathStatus -eq 'toolong' -or $pathStatus -eq 'failed') {
Warn 'Add these entries to PATH yourself, or call python.exe by its full path:'
$toAdd | ForEach-Object { Write-Host " $_" }
$exitCode = 2
}
# 9) Verify
Write-Host ''
Write-Host 'Verifying Python...'
& $pyExe -V
if ($LASTEXITCODE -ne 0) { Fail 'Python executable exists but failed to run.' }
Write-Host 'Verifying pip...'
& $pyExe -m pip --version 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host ' pip missing, trying ensurepip...'
try { & $pyExe -m ensurepip --upgrade 2>$null | Out-Null } catch {}
& $pyExe -m pip --version
if ($LASTEXITCODE -ne 0) { Fail 'pip is not working correctly.' }
}
# 10) Hand results back to the batch part
$sessAdd = $toAdd -join ';'
if (([Environment]::GetEnvironmentVariable('Path', 'Process')).Length -gt $SessionPathMax) {
Set-Flag '.nosession'
}
Set-Content -LiteralPath $ResultFile -Value @((Join-Path $pathDir 'python.exe'), $sessAdd) -Encoding OEM
exit $exitCode
} catch {
Fail $_.Exception.Message
}