Repository navigation
Expand file tree
/
Copy pathPyVersions.ps1
More file actions
1944 lines (1777 loc) · 96 KB
/
Copy pathPyVersions.ps1
File metadata and controls
1944 lines (1777 loc) · 96 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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =========================================================
# PyVersions v1.8.5 (定稿)
# Python 独立版 (install_only) 多版本管理工具
# 下载源: astral-sh/python-build-standalone (持续更新)
#
# 主菜单功能:
# [1] 部署 Python - 本地离线包 + 在线下载 融合入口:
# 编号 / 精确版本 (如 3.12.16) 优先使用本地离线包 (本地没有转在线),
# 大版本 (如 3.12) 在线优先获取最新构建 (本地缓存命中免下载,
# 断网自动降级本地离线包), o [版本] 强制在线, 无离线包时直接在线;
# 解压自检通过才安装 (缺陷构建自动回退次新构建),
# 按版本自动命名安装目录 (如 D:\Python\python3.12, 支持多版本共存,
# 目录已存在时可选择 覆盖安装 / 跳过部署 / 更换目录),
# 自动创建 Scripts\pip*.bat, 自动导入注册表与 PATH
# [2] 清理 / 卸载指定版本 - 二选一: 仅清理注册表键 / 文件关联 / PATH,
# 或连同安装目录文件一起删除 (卸载需输入版本号二次确认;
# 被其他版本共享的安装目录只清理注册项, 文件保留)
# [3] 查看本机已注册版本 - 扫描 HKLM/HKCU 注册表与 PATH,
# 可将指定版本设为主用 (PATH 置前 + .py 关联指向)
#
# 运行方式: powershell.exe -ExecutionPolicy Bypass -File PyVersions.ps1 [版本号]
# 启动参数: PyVersions.ps1 3.12 直接部署 3.12 系列 (大版本语义: 在线优先+断网降级)
# PyVersions.ps1 3.12.16 直接部署精确版本 (本地优先, 无则在线)
# PyVersions.ps1 --help 显示帮助; 无参数进入交互主菜单
# 系统要求: Windows 10 (1803+) / Windows 11 / Windows Server 2019/2022/2025
# (系统自带 curl 与 tar, 开箱即用), 不支持更早版本系统
#
# 注意: 本文件必须以 UTF-8 with BOM 编码保存,
# 否则中文在 Windows PowerShell 5.1 下会乱码
# =========================================================
param(
[Parameter(Position = 0)][string]$InputVersion = "", # 启动参数: 直接部署指定版本, 空则进入交互菜单
[switch]$Help # 显示帮助
)
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
trap {
Write-Host ""
Write-Host "[致命错误] $($_.Exception.Message)" -ForegroundColor Red
Write-Host "出错位置: 第 $($_.InvocationInfo.ScriptLineNumber) 行: $($_.InvocationInfo.Line.Trim())" -ForegroundColor DarkGray
Read-Host "按回车键退出"
exit 1
}
if ($PSScriptRoot) { Set-Location -Path $PSScriptRoot }
# ----------------------- 配置区 -----------------------
# 资源仓库 (数组形式便于日后扩展备用源; 当前仅使用单一源)
$RepoSlugs = @("astral-sh/python-build-standalone")
$ExtractParentDir = "D:\Python" # 安装/解压父目录 (压缩包内含 python\ 顶层目录)
$TargetArch = "x86_64-pc-windows-msvc-install_only.tar.gz" # 目标资源后缀
$DefaultVersion = "3.12" # 直接回车时使用的默认版本
# 安装目录备选根 (对应官方 Python 安装器路径惯例, 安装目录 = 备选根\Python<XY>, 如 Python312)
$AllUsersRoot = if ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } # All Users 安装 (需管理员); ProgramW6432 避开 32 位进程的 WOW64 重定向
$UserRoot = Join-Path $env:LOCALAPPDATA "Programs\Python" # 当前用户安装 (无需管理员)
# 下载加速线路 (按顺序尝试; 留空字符串表示 GitHub 直连。镜像失效会自动换下一线路)
$DownloadMirrors = @("", "https://ghfast.top/", "https://gh-proxy.com/")
# 局域网代理加速 (优先于系统代理; 逐个 TCP 探测, 200ms 内连通即启用)
$GlobalProxyUrls = @(
"http://localhost:56666",
"http://192.168.1.10:56666",
"http://192.168.1.88:56666",
"http://10.175.167.167:56666"
)
# 探测超时(毫秒): 与 .sh 的 timeout 0.2s 对齐 = 200ms; 注意单位是毫秒, 勿误填 0.2 (那是 0.2ms 恒失败)
$ProxyProbeTimeoutMs = 200
# -------------------------------------------------------
$SevenZipExe = "C:\Program Files\7-Zip\7z.exe"
$TarExe = Join-Path $env:SystemRoot "System32\tar.exe"
# ======================= 基础工具函数 =======================
function Write-Banner([string]$text, [string]$color = "Cyan") {
Write-Host "=========================================" -ForegroundColor $color
Write-Host $text -ForegroundColor $color
Write-Host "=========================================" -ForegroundColor $color
}
# 计算字符串的控制台显示宽度 (CJK 等全角字符按 2 列计, 用于菜单项对齐)
function Get-DisplayWidth([string]$s) {
$w = 0
foreach ($ch in $s.ToCharArray()) {
if ([int]$ch -ge 0x2E80) { $w += 2 } else { $w += 1 }
}
return $w
}
# 读取一行用户输入并去除首尾空白; 输入流结束 (EOF) 时返回 $null
function Read-Input([string]$prompt) {
$v = Read-Host $prompt
if ($null -eq $v) { return $null }
return $v.Trim()
}
# 循环读取 Y/N 确认; 输入流结束 (EOF) 时返回 "N" 以防误操作
function Read-YesNo([string]$prompt, [string]$default = "Y") {
while ($true) {
$v = Read-Input "$prompt (Y/N) [默认: $default]"
if ($null -eq $v) { return "N" }
if ([string]::IsNullOrWhiteSpace($v)) { $v = $default }
$v = $v.Substring(0, 1).ToUpper()
if ($v -eq "Y" -or $v -eq "N") { return $v }
Write-Host "请输入 Y 或 N。" -ForegroundColor Red
}
}
function Test-IsAdmin {
return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
# 广播环境变量变更 (WM_SETTINGCHANGE), 让新开终端立即识别, 无需注销/重启
function Invoke-EnvBroadcast {
try {
if (-not ('Win32.Win32Broadcast' -as [type])) {
$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
Add-Type -MemberDefinition $sig -Name "Win32Broadcast" -Namespace "Win32" | Out-Null
}
$broadcast = 'Win32.Win32Broadcast' -as [type]
[UIntPtr]$result = [UIntPtr]::Zero
$null = $broadcast::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, "Environment", 2, 5000, [ref]$result)
Write-Host "[成功] 已广播环境变量变更, 新开的终端即刻生效 (已开着的终端需重开)。" -ForegroundColor Green
} catch {
Write-Host "[提示] 环境变量变更广播失败 (不影响写入), 重新打开终端即可生效。" -ForegroundColor DarkYellow
}
}
# 获取单个资源压缩包: 本地已有同名文件(>1MB)则直接复用不重复下载,
# 否则按 直连/镜像 依次尝试下载。成功返回本地路径, 失败返回 $null
function Invoke-AssetDownload([string]$assetName, [string]$assetUrl) {
$pa = $script:CurlProxyArgs # 按次传入代理 (-x), 不依赖/不改写环境变量
if (Test-Path $assetName) {
$localItem = Get-Item $assetName -ErrorAction SilentlyContinue
if ($localItem -and $localItem.Length -gt 1MB) {
$localPath = (Resolve-Path $assetName).Path
Write-Host "发现本地已有同名压缩包, 跳过下载: $localPath" -ForegroundColor Green
return $localPath
}
# 本地文件过小 (下载残留/损坏), 删除后重新下载
Remove-Item $assetName -Force -ErrorAction SilentlyContinue
}
# curl.exe 前置检查: Windows 10 1803+ / Server 2019+ 系统自带, 更早版本系统请升级后再使用
if (-not (Get-Command curl.exe -ErrorAction SilentlyContinue)) {
Write-Host "[错误] 未找到 curl.exe, 无法下载。" -ForegroundColor Red
Write-Host " 本工具要求 Windows 10 (1803+) / Windows 11 / Server 2019 及以上系统 (自带 curl)。" -ForegroundColor Red
return $null
}
foreach ($mirror in $DownloadMirrors) {
$tryUrl = "$mirror$assetUrl"
if ($mirror) { Write-Host "正在通过加速镜像下载: $mirror" -ForegroundColor Cyan }
else { Write-Host "正在通过 GitHub 直连下载..." -ForegroundColor Cyan }
& curl.exe @pa -f -L --retry 3 --retry-delay 2 --connect-timeout 20 --ssl-no-revoke -o "$assetName" "$tryUrl"
if ($LASTEXITCODE -eq 0 -and (Test-Path $assetName) -and ((Get-Item $assetName).Length -gt 1MB)) {
$okPath = (Resolve-Path $assetName).Path
Write-Host "下载完成: $okPath" -ForegroundColor Green
return $okPath
}
Write-Host "该线路下载失败, 尝试下一线路..." -ForegroundColor Yellow
if (Test-Path $assetName) { Remove-Item $assetName -Force -ErrorAction SilentlyContinue }
}
return $null
}
# ======================= 注册表扫描 =======================
# 扫描注册表 (HKLM / HKLM 32位视图 / HKCU) 中已注册的 Python (PEP 514 PythonCore)
function Get-RegisteredPythons {
$result = @()
$hives = @(
@{ Root = "HKLM:\SOFTWARE\Python\PythonCore"; Label = "HKLM" },
@{ Root = "HKLM:\SOFTWARE\WOW6432Node\Python\PythonCore"; Label = "HKLM(32)" },
@{ Root = "HKCU:\Software\Python\PythonCore"; Label = "HKCU" }
)
foreach ($h in $hives) {
if (-not (Test-Path $h.Root)) { continue }
foreach ($tagKey in @(Get-ChildItem -Path $h.Root -ErrorAction SilentlyContinue)) {
$p = Get-ItemProperty -Path $tagKey.PSPath -ErrorAction SilentlyContinue
$ipKey = Join-Path $tagKey.PSPath "InstallPath"
$installPath = ""
if (Test-Path $ipKey) {
$installPath = ([string]((Get-Item -Path $ipKey).GetValue("")))
if ($installPath -match '[\r\n"]') {
# 清洗历史残缺值: 形如 "路径" /f 或含换行的损坏注册, 取引号内/首个路径段
$installPath = (($installPath -split '\r?\n')[0] -split '"\s+')[0].Trim().Trim('"').Trim()
}
$installPath = $installPath.TrimEnd("\")
}
$result += [PSCustomObject]@{
Hive = $h.Label
Tag = $tagKey.PSChildName
DisplayName = [string]$p.DisplayName
Version = [string]$p.Version
SysVersion = [string]$p.SysVersion
InstallPath = $installPath
KeyPath = $tagKey.PSPath
}
}
}
return ,$result
}
# 按 "3.12" (tag / SysVersion) 或 "3.12.16" (完整版本号) 匹配已注册 Python
function Get-MatchedRegistrations([string]$inputVer) {
# 注意: 必须先赋值再过滤。直接写 Get-RegisteredPythons | Where-Object 会让
# 整个数组作为单个 $_ 进入管道, 成员枚举导致所有注册都被错误匹配
$esc = [regex]::Escape($inputVer)
$registered = Get-RegisteredPythons
return @($registered | Where-Object {
($_.Tag -eq $inputVer) -or
($_.Version -eq $inputVer) -or
($_.SysVersion -eq $inputVer) -or
($inputVer -match '^[0-9]+\.[0-9]+$' -and $_.Tag -match "^${esc}(\.|-|$)")
})
}
# 判断 PATH 条目是否位于 root 之下 (root 本身 / root\Scripts / root 的子目录段, 大小写不敏感)
function Test-PathUnder([string]$entry, [string]$root) {
$e = $entry.TrimEnd("\"); $r = $root.TrimEnd("\")
if (-not $r) { return $false }
return ($e -ieq $r -or $e -match ("^" + [regex]::Escape($r) + "(\\.+)?$"))
}
# 展示已注册 Python 列表与 PATH 中的 Python 相关条目 (功能 3 / 清理前预览)
function Show-RegisteredPythons {
$registered = Get-RegisteredPythons
if ($registered.Count -eq 0) {
Write-Host "注册表中未发现任何 PythonCore 注册信息 (HKLM/HKCU 均无)。" -ForegroundColor Yellow
} else {
Write-Host "注册表中的 Python (PEP 514 PythonCore):" -ForegroundColor White
foreach ($r in $registered) {
$ver = if ($r.Version) { $r.Version } else { "(版本未知)" }
$ip = if ($r.InstallPath) { $r.InstallPath } else { "(InstallPath 缺失, 疑似残留残键)" }
Write-Host (" [{0,-7}] {1,-8} 版本 {2,-12} 安装目录: {3}" -f $r.Hive, $r.Tag, $ver, $ip)
}
}
Write-Host ""
Write-Host "PATH 中的 Python 相关条目:" -ForegroundColor White
$foundAny = $false
foreach ($target in @([EnvironmentVariableTarget]::Machine, [EnvironmentVariableTarget]::User)) {
$raw = [Environment]::GetEnvironmentVariable("Path", $target)
if (-not $raw) { continue }
foreach ($e in @($raw -split ";")) {
if ($e -and $e -match "(?i)python") {
Write-Host (" [{0}] {1}" -f $target, $e)
$foundAny = $true
}
}
}
if (-not $foundAny) { Write-Host " (无)" }
}
# ====== 下载代理解析 (局域网代理优先 -> 系统代理 -> 直连) ======
# 探测局域网代理: 逐个 TCP 连通性测试, 返回第一个可用地址 (无则 $null)
function Get-AvailableProxy {
foreach ($proxy in $GlobalProxyUrls) {
$tcpClient = $null
try {
$uri = [Uri]$proxy
$tcpClient = [System.Net.Sockets.TcpClient]::new()
$connectTask = $tcpClient.ConnectAsync($uri.Host, $uri.Port)
if ($connectTask.Wait($ProxyProbeTimeoutMs) -and $tcpClient.Connected) {
return $proxy
}
} catch {
} finally {
if ($null -ne $tcpClient) {
try { $tcpClient.Close() } catch { }
try { $tcpClient.Dispose() } catch { }
}
}
}
return $null
}
# 每次进入在线流程前调用: 解析下载代理。结果按次传给 curl (-x) / Invoke-RestMethod (-Proxy),
# 不改写 http_proxy/https_proxy 环境变量, 也不改动系统代理配置 (局域网代理只是"拿来用", 不是"替换")
function Set-DownloadProxy {
$script:ActiveProxy = ""
$script:CurlProxyArgs = @()
# 1. 用户预设的代理环境变量: 直接沿用 (优先级最高, 不做任何改动)
# (Windows 环境变量名不区分大小写, $env:http_proxy 已涵盖 HTTP_PROXY/HTTPS_PROXY)
if ($env:http_proxy -or $env:https_proxy) {
$srcVar = if ($env:http_proxy) { "http_proxy" } else { "https_proxy" }
$script:ActiveProxy = if ($env:http_proxy) { $env:http_proxy } else { $env:https_proxy }
$script:CurlProxyArgs = @("-x", $script:ActiveProxy)
Write-Host "使用预设代理环境变量 ($srcVar): $script:ActiveProxy (不改动任何配置)" -ForegroundColor DarkGray
return
}
# 2. 局域网代理探测: 连通即用于本次下载
$lanProxy = Get-AvailableProxy
if ($lanProxy) {
$script:ActiveProxy = $lanProxy
$script:CurlProxyArgs = @("-x", $lanProxy)
Write-Host "已启用局域网代理加速: $lanProxy (仅用于本次下载, 不改动系统代理配置)" -ForegroundColor Green
return
}
Write-Host "未发现可用的局域网代理, 尝试系统代理..." -ForegroundColor DarkGray
# 3. 系统代理 (WinINET): 读取后同样按次使用, 不写回任何配置
$regProxy = Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -ErrorAction SilentlyContinue
if ($regProxy.ProxyEnable -eq 1 -and $regProxy.ProxyServer) {
$rawProxy = ($regProxy.ProxyServer -split ';')[0]
$sysProxy = if ($rawProxy -match '=') { ($rawProxy -split '=')[1] } else { $rawProxy }
if ($sysProxy -notmatch '^https?://') { $sysProxy = "http://$sysProxy" }
$script:ActiveProxy = $sysProxy
$script:CurlProxyArgs = @("-x", $sysProxy)
Write-Host "已检测到系统代理并按次应用: $sysProxy (不改动其配置)" -ForegroundColor Green
} else {
Write-Host "未启用任何代理, 将使用直连/TUN 模式。" -ForegroundColor Yellow
}
}
# ====== 上游构建发现 (零 API 优先, 参考 PyVersions_pyenv.sh 统一策略) ======
# 获取指定 Release tag 的 SHA256SUMS 清单 (%TEMP%\PyVersions_sums 缓存复用, 仅几十 KB); 失败返回 $null
function Get-SumsFile([string]$tag) {
$pa = $script:CurlProxyArgs
$sumsDir = Join-Path $env:TEMP "PyVersions_sums"
if (-not (Test-Path $sumsDir)) {
New-Item -ItemType Directory -Path $sumsDir -Force -ErrorAction SilentlyContinue | Out-Null
}
$cached = Join-Path $sumsDir "SHA256SUMS-$tag"
if (Test-Path $cached) { return $cached }
$sumsUrl = "https://github.com/astral-sh/python-build-standalone/releases/download/$tag/SHA256SUMS"
foreach ($mirror in $DownloadMirrors) {
$tmp = "$cached.part"
& curl.exe @pa -fsSL --retry 2 --connect-timeout 12 "${mirror}${sumsUrl}" -o "$tmp" 2>$null
if ($LASTEXITCODE -eq 0 -and (Test-Path $tmp) -and (Get-Item $tmp).Length -gt 0) {
Move-Item -Path $tmp -Destination $cached -Force
return $cached
}
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
}
return $null
}
# 轻量上游发现 (零 API, 不受限流影响):
# releases/latest 302 重定向取最新 tag + releases.atom 取次新 tag -> SHA256SUMS 文件名精确匹配。
# 失败细节写入 $script:NetworkErrors / $script:AnyRepoOk / $script:SampleNames 供报错展示。
function Get-UpstreamCandidatesLight([string]$inputVer) {
$script:SampleNames = @(); $script:NetworkErrors = @(); $script:AnyRepoOk = $false
$ownerRepo = "astral-sh/python-build-standalone"
$tags = @()
$pa = $script:CurlProxyArgs # 按次传入代理 (-x), 不依赖/不改写环境变量
# 1) releases/latest 302 重定向取最新 tag
$headOut = (& curl.exe @pa -sI --connect-timeout 10 "https://github.com/$ownerRepo/releases/latest" 2>$null | Out-String)
if ($headOut -match 'location:\s*\S*?tag/([0-9]{8})') { $tags += $Matches[1] }
# 2) releases.atom 取最近 3 个 tag (多线路, 兼作次新构建回退来源)
foreach ($mirror in $DownloadMirrors) {
$atom = (& curl.exe @pa -fsSL --connect-timeout 10 "${mirror}https://github.com/$ownerRepo/releases.atom" 2>$null | Out-String)
if ($atom) {
$atomTags = @([regex]::Matches($atom, 'releases/tag/([0-9]{8})') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
foreach ($t in $atomTags) {
if ($tags -inotcontains $t) { $tags += $t }
if ($tags.Count -ge 3) { break }
}
if ($tags.Count -ge 2) { break }
}
}
if ($tags.Count -eq 0) {
$script:NetworkErrors += "轻量发现: 未能获取任何 Release 标签 (网络不通或镜像不可用)"
return @()
}
$script:AnyRepoOk = $true
# 3) 逐 tag 检索 SHA256SUMS, 按文件名精确匹配 (大版本匹配 x.y.* / 精确版本锁定)
$escapedVer = [regex]::Escape($inputVer)
$escapedArch = [regex]::Escape($TargetArch)
if ($inputVer -match '^[0-9]+\.[0-9]+$') {
$pat = "^c?python-${escapedVer}\.[0-9]+\+"
} else {
$pat = "^c?python-${escapedVer}\+"
}
$candidates = @()
foreach ($t in $tags) {
$sumsFile = Get-SumsFile $t
if (-not $sumsFile) { continue }
foreach ($line in @(Get-Content $sumsFile -ErrorAction SilentlyContinue)) {
# SHA256SUMS 行格式: <sha256><空白><空格或*>文件名
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') {
$fname = $Matches[2].Trim()
if ($fname -notmatch ($pat + $t + "-" + $escapedArch + "$")) { continue }
if ($fname -notmatch '^c?python-([0-9]+\.[0-9]+\.[0-9]+)\+') { continue }
$candidates += [PSCustomObject]@{
Name = $fname
Url = "https://github.com/$ownerRepo/releases/download/$t/$fname"
PyVer = [version]$Matches[1]
BuildDate = [int64]($t + "000000")
Tag = $t
Repo = $ownerRepo
}
}
}
if ($candidates.Count -ge 2) { break } # 最新 tag 已命中, 无需更多
}
return @($candidates |
Sort-Object -Property @{ Expression = "PyVer"; Descending = $true }, @{ Expression = "BuildDate"; Descending = $true })
}
# GitHub API 发现 (回退线路: 轻量发现无结果时使用, 覆盖 atom 时效外的历史版本)
# 失败细节写入 $script:NetworkErrors / $script:AnyRepoOk / $script:SampleNames
function Get-UpstreamCandidatesViaApi([string]$inputVer) {
$script:SampleNames = @(); $script:NetworkErrors = @(); $script:AnyRepoOk = $false
$escapedVer = [regex]::Escape($inputVer)
$escapedArch = [regex]::Escape($TargetArch)
# 版本号后必须紧跟 + 或 -, 以排除 3.16.0a1 / 3.14.0rc1 等预发布版
if ($inputVer -match '^[0-9]+\.[0-9]+$') {
$namePattern = "^c?python-${escapedVer}\.[0-9]+[\+\-].*${escapedArch}$"
} else {
$namePattern = "^c?python-${escapedVer}[\+\-].*${escapedArch}$"
}
$candidates = @()
$headers = @{
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
"Accept" = "application/vnd.github+json"
}
foreach ($slug in $RepoSlugs) {
Write-Host "正在查询仓库: $slug ..." -ForegroundColor Cyan
$apiBase = "https://api.github.com/repos/$slug/releases"
$repoFailed = $false
for ($page = 1; $page -le 3; $page++) {
$uri = "${apiBase}?per_page=15&page=$page"
$releases = $null
$lastErr = $null
# 每次请求自动重试 3 次, 应对网络波动 / 网关超时
for ($attempt = 1; $attempt -le 3; $attempt++) {
try {
$irmArgs = @{ Uri = $uri; Headers = $headers; TimeoutSec = 40 }
if ($script:ActiveProxy) { $irmArgs["Proxy"] = $script:ActiveProxy } # 按次传入代理, .NET 管线同样生效
$releases = Invoke-RestMethod @irmArgs
$lastErr = $null
break
} catch {
$lastErr = $_.Exception.Message
if ($attempt -lt 3) {
Write-Host " 查询失败 (第 $attempt/3 次): $lastErr" -ForegroundColor DarkYellow
Write-Host " 3 秒后自动重试..." -ForegroundColor DarkYellow
Start-Sleep -Seconds 3
}
}
}
if ($null -ne $releases) {
foreach ($rel in @($releases)) {
if ($rel.draft) { continue }
$relDate = [int64]0
try {
$relDate = [int64]([DateTimeOffset]::Parse($rel.published_at, [Globalization.CultureInfo]::InvariantCulture).UtcDateTime.ToString("yyyyMMddHHmmss"))
} catch {}
foreach ($asset in @($rel.assets)) {
if ($script:SampleNames.Count -lt 3 -and $asset.name -like "*.tar.gz") { $script:SampleNames += $asset.name }
if ($asset.name -notmatch $namePattern) { continue }
$pyVerStr = $null
if ($asset.name -match "^c?python-([0-9]+\.[0-9]+\.[0-9]+)[\+\-]") { $pyVerStr = $Matches[1] }
if (-not $pyVerStr) { continue }
$buildDate = $relDate
if ($asset.name -match "[\+\-]([0-9]{8})[\+\-]") { $buildDate = [int64]($Matches[1] + "000000") }
$candidates += [PSCustomObject]@{
Name = $asset.name
Url = $asset.browser_download_url
PyVer = [version]$pyVerStr
BuildDate = $buildDate
Tag = $rel.tag_name
Repo = $slug
}
}
}
} elseif ($lastErr) {
# 该仓库查询彻底失败 (已重试), 记录错误详情
$repoFailed = $true
break
} else {
# 分页已取完
break
}
if ($candidates.Count -gt 0) { break }
}
if ($repoFailed) {
$script:NetworkErrors += "${slug}: $lastErr"
Write-Host "仓库 $slug 查询失败。" -ForegroundColor Yellow
} else {
$script:AnyRepoOk = $true
}
if ($candidates.Count -gt 0) { break }
}
return $candidates
}
# ====== 完整性校验与缓存治理 ======
# SHA256 完整性校验: SHA256SUMS 有对应清单项时强制校验; 清单不可得时放行 (部署自检仍会兜底)。
# 返回 $true = 通过 (或无法校验); $false = 校验失败 (坏包已删除, 调用方可回退下一候选)
function Test-ArchiveSha256([string]$archiveFilePath, [object]$cand) {
$sumsFile = Get-SumsFile $cand.Tag
if (-not $sumsFile) {
Write-Host "[提示] 未能获取 SHA256SUMS, 跳过完整性校验 (部署自检仍会执行)。" -ForegroundColor DarkYellow
return $true
}
$expected = $null
foreach ($line in @(Get-Content $sumsFile -ErrorAction SilentlyContinue)) {
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') {
if ($Matches[2].Trim() -eq $cand.Name) { $expected = $Matches[1].ToLower(); break }
}
}
if (-not $expected) { return $true } # 清单中无此项, 放行
$actual = (Get-FileHash -Path $archiveFilePath -Algorithm SHA256).Hash.ToLower()
if ($actual -ne $expected) {
Write-Host "[警告] SHA256 校验失败: $($cand.Name)" -ForegroundColor Red
Write-Host " 期望: $expected" -ForegroundColor Red
Write-Host " 实际: $actual" -ForegroundColor Red
Remove-Item $archiveFilePath -Force -ErrorAction SilentlyContinue
return $false
}
Write-Host "SHA256 校验通过" -ForegroundColor Green
return $true
}
# 缓存治理: 部署成功后清理同精确版本的旧日期缓存包 (仅保留本次使用的最新包)
function Remove-StaleCaches([string]$pyFullVer, [string]$keepName) {
$filter = "cpython-$pyFullVer+*-$TargetArch"
Get-ChildItem -Path $PSScriptRoot -Filter $filter -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -ne $keepName } |
ForEach-Object {
Write-Host "清理同版本旧日期缓存: $($_.Name)" -ForegroundColor DarkYellow
Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
}
}
# ============ 功能 1 内部: 在线部署执行体 (供统一部署流程调用) ============
# 在线部署执行体: 代理检测 -> 选版本 -> 查询 GitHub -> 下载/缓存 -> 部署。
# 返回 $true = 版本已部署 (或保留现有安装); $false = 未完成部署 (统一部署流程可据此降级本地)
function Invoke-InstallFlow([string]$presetVersion = "") {
# ---------- 1. 下载代理解析 (局域网代理优先 -> 系统代理 -> 直连) ----------
Write-Banner "1. 正在解析下载代理..."
Set-DownloadProxy
Write-Host ""
# ---------- 2. 选择 Python 版本 ----------
Write-Banner "2. 选择 Python 版本"
Write-Host "提示:"
Write-Host " - 输入 大版本.小版本 (如 3.12) -> 自动选择 3.12.x 中补丁号最高、构建日期最新的包"
Write-Host " - 输入 完整版本号 (如 3.12.13) -> 下载 3.12.13 中构建日期最新的包"
Write-Host " - 直接回车 -> 默认使用 $DefaultVersion"
Write-Host ""
$inputVer = $null
# 支持从其他流程 (如离线部署失败转在线) 预置版本号, 跳过手动输入
if ($presetVersion -match '^[0-9]+\.[0-9]+(\.[0-9]+)?$') {
$inputVer = $presetVersion
Write-Host "使用指定版本: $inputVer" -ForegroundColor Cyan
}
while ($null -eq $inputVer) {
$inputVer = Read-Input "请输入 Python 版本 [默认: $DefaultVersion]"
if ($null -eq $inputVer) {
Write-Host "输入已结束, 返回主菜单。" -ForegroundColor Yellow
return $false
}
if ([string]::IsNullOrWhiteSpace($inputVer)) { $inputVer = $DefaultVersion }
if ($inputVer -match '^[0-9]+\.[0-9]+(\.[0-9]+)?$') { break }
Write-Host "版本号格式无效: [$inputVer], 请输入类似 3.12 或 3.12.13 的格式。" -ForegroundColor Red
$inputVer = $null
}
Write-Host ""
# ---------- 3. 查询上游构建 (零 API 优先, GitHub API 回退) ----------
Write-Banner "3. 正在查询上游构建 [$inputVer] ..."
$candidates = @(Get-UpstreamCandidatesLight $inputVer)
if ($candidates.Count -gt 0) {
Write-Host "轻量发现命中 $($candidates.Count) 个候选构建 (零 API, 不受限流影响)。" -ForegroundColor Green
} else {
Write-Host "轻量发现无结果, 回退 GitHub API 查询..." -ForegroundColor Yellow
$candidates = @(Get-UpstreamCandidatesViaApi $inputVer)
}
$bestMatch = $candidates |
Sort-Object -Property @{ Expression = "PyVer"; Descending = $true }, @{ Expression = "BuildDate"; Descending = $true } |
Select-Object -First 1
if (-not $bestMatch) {
Write-Host ""
if (-not $script:AnyRepoOk) {
Write-Host "[错误] 上游检索失败 (轻量 + API 均未成功):" -ForegroundColor Red
$script:NetworkErrors | ForEach-Object { Write-Host " - $_" -ForegroundColor Red }
Write-Host "可能原因: 网络不稳定 / 代理未生效。" -ForegroundColor Yellow
} else {
Write-Host "[错误] 仓库中未找到匹配 [$inputVer] 且后缀为 [$TargetArch] 的资源。" -ForegroundColor Red
if ($script:SampleNames.Count -gt 0) {
Write-Host "源中部分 .tar.gz 资源名示例:" -ForegroundColor Yellow
$script:SampleNames | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
} else {
Write-Host "未获取到任何 .tar.gz 资源, 请检查网络后重试。" -ForegroundColor Yellow
}
}
return $false
}
Write-Host ""
Write-Host "匹配成功!" -ForegroundColor Green
Write-Host "来源仓库 : $($bestMatch.Repo)"
Write-Host "Release 标签: $($bestMatch.Tag)"
Write-Host "目标文件 : $($bestMatch.Name)"
Write-Host ""
# ---------- 4. 获取压缩包 (本地已有则复用) ----------
Write-Banner "4. 获取压缩包 (本地已有则跳过下载)"
$archiveFilePath = Invoke-AssetDownload $bestMatch.Name $bestMatch.Url
if (-not $archiveFilePath) {
# 首选构建获取失败不再直接中止, 交由候选队列尝试次新构建
Write-Host "[警告] 首选构建获取失败, 将尝试次新候选构建..." -ForegroundColor Yellow
}
Write-Host ""
# ---------- 5. 部署 (SHA256 校验 + 解压自检, 缺陷构建自动回退) ----------
Write-Banner "5. 部署 Python"
Write-Host "将安装: $($bestMatch.Name)"
# 安装目录: 默认 D:\Python\python<tag> (如 python3.12), 支持多版本共存, 可自定义
$pyTagInput = $inputVer
if ($inputVer -match '^([0-9]+\.[0-9]+)') { $pyTagInput = $Matches[1] }
$sel = Get-InstallDestDir $pyTagInput
if ($null -eq $sel) { return $false }
if ($sel.Skip) {
Write-Host "已保留现有安装, 跳过部署。压缩包保留在: $archiveFilePath" -ForegroundColor Yellow
return $true
}
$destDir = $sel.Dir
# 候选构建队列: 最优匹配在前, 最多尝试 3 个构建 (应对个别构建自检不通过)
$deployQueue = @($bestMatch) + @($candidates | Where-Object { $_.Name -ne $bestMatch.Name } | Select-Object -First 2)
$installedName = $null
foreach ($cand in $deployQueue) {
if ($cand.Name -ne $bestMatch.Name) {
Write-Host ""
Write-Host "自动回退, 尝试次新构建: $($cand.Name)" -ForegroundColor Cyan
if (Test-Path $archiveFilePath) { Remove-Item $archiveFilePath -Force -ErrorAction SilentlyContinue }
$archiveFilePath = Invoke-AssetDownload $cand.Name $cand.Url
if (-not $archiveFilePath) {
Write-Host "[警告] 回退构建获取失败, 尝试下一个..." -ForegroundColor Yellow
continue
}
}
if ($null -eq $archiveFilePath) { continue }
# SHA256 完整性校验 (坏包自动删除, 回退下一候选)
if (-not (Test-ArchiveSha256 $archiveFilePath $cand)) { continue }
if (Invoke-DeployPipeline $archiveFilePath $destDir) { $installedName = $cand.Name; break }
}
if (-not $installedName) {
Write-Host "[错误] 所有候选构建均部署失败 (下载失败或自检未通过), 请稍后重试。" -ForegroundColor Red
return $false
}
if ($installedName -ne $bestMatch.Name) {
Write-Host "[提示] 最新构建 $($bestMatch.Name) 未通过自检, 已自动回退安装: $($installedName)" -ForegroundColor Yellow
}
# 缓存治理: 清理同版本旧日期缓存包, 仅保留本次使用的最新包
if ($installedName -match '^c?python-([0-9]+\.[0-9]+\.[0-9]+)\+') {
Remove-StaleCaches $Matches[1] $installedName
}
Write-Host ""
return $true
}
# ============== 部署共用: 安装目录交互 + 部署管线 (本地 / 在线统一使用) ===============
# 询问安装目录 (默认 D:\Python\python<tag>; 已存在时 O/K/N 交互)。
# 返回 @{ Dir = 安装目录; Skip = 是否保留现有跳过部署 }; 输入流结束 (EOF) 返回 $null
function Get-InstallDestDir([string]$pyTagInput) {
$tagCompact = $pyTagInput -replace '\.', '' # 3.12 -> 312
$defaultDest = Join-Path $ExtractParentDir "python$pyTagInput"
# 备选目录: 本工具默认 + 官方 Python 安装器惯例路径 (All Users / 当前用户)
$allUsersNote = "(官方惯例, All Users)"
if (-not (Test-IsAdmin)) { $allUsersNote = "(官方惯例, All Users - 需管理员权限)" }
$options = @(
@{ Dir = $defaultDest; Note = "(本工具默认)" },
@{ Dir = Join-Path $AllUsersRoot "Python$tagCompact"; Note = $allUsersNote },
@{ Dir = Join-Path $UserRoot "Python$tagCompact"; Note = "(官方惯例, 当前用户)" }
)
while ($true) {
Write-Host ""
Write-Host "请选择安装目录 [直接回车 = 1]:" -ForegroundColor White
for ($i = 0; $i -lt $options.Count; $i++) {
Write-Host (" [{0}] {1} {2}" -f ($i + 1), $options[$i].Dir, $options[$i].Note) -ForegroundColor DarkGray
}
Write-Host " 或直接输入自定义路径" -ForegroundColor DarkGray
$dirInput = Read-Input "请输入编号或路径"
if ($null -eq $dirInput) { return $null }
if ([string]::IsNullOrWhiteSpace($dirInput)) {
$destDir = $defaultDest
} elseif ($dirInput -match '^[0-9]+$' -and [int]$dirInput -ge 1 -and [int]$dirInput -le $options.Count) {
$destDir = $options[[int]$dirInput - 1].Dir
} elseif ([System.IO.Path]::IsPathRooted($dirInput)) {
$destDir = $dirInput.TrimEnd("\")
} else {
$destDir = (Join-Path $ExtractParentDir $dirInput).TrimEnd("\")
}
# 目录合法性检查 (排除非法字符, 盘符冒号除外)
$checkPart = $destDir -replace '^[A-Za-z]:', ''
if ($checkPart.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -ge 0 -or $checkPart -match '[<>:"|?*]') {
Write-Host "目录路径含非法字符: [$destDir], 请重新输入。" -ForegroundColor Red
continue
}
# 目标位置可达性检查: 本地盘符必须已挂载 / UNC 共享前两级必须可达
# (提前拦截, 避免解压自检全部通过后才在移动阶段失败)
$checkRoot = $null
if ($destDir -match '^([A-Za-z]:)') { $checkRoot = $Matches[1] + "\" }
elseif ($destDir -match '^\\\\[^\\]+\\[^\\]+') { $checkRoot = $Matches[0] }
if ($checkRoot -and -not (Test-Path -LiteralPath $checkRoot)) {
Write-Host "目标位置不可达 (磁盘不存在或共享不可用): $checkRoot, 请重新输入。" -ForegroundColor Red
continue
}
# 拒绝盘根 / 裸盘符 / UNC 共享根作为安装目录 (覆盖模式会清空整个目标, 防灾难性误删)
if ($destDir -match '^[A-Za-z]:$' -or $destDir -match '^\\\\[^\\]+\\[^\\]+$') {
Write-Host "不能把安装目录设在根目录: [$destDir], 请指定一个子目录 (如 ${destDir}\Python\python$pyTagInput)。" -ForegroundColor Red
continue
}
if (Test-Path $destDir) {
Write-Host ""
Write-Host "目标目录已存在: $destDir" -ForegroundColor Yellow
Write-Host " [O] 覆盖安装 (清理后全新安装, pip 已装的第三方包不保留)"
Write-Host " [K] 保留现有安装, 跳过部署 [默认]"
Write-Host " [N] 更换安装目录"
$act = Read-Input "请选择"
if ($null -eq $act) { return $null }
if ([string]::IsNullOrWhiteSpace($act)) { $act = "K" }
$act = $act.Substring(0, 1).ToUpper()
if ($act -eq "K") { return @{ Dir = $destDir; Skip = $true } }
if ($act -eq "N") { continue } # 重新输入目录
# O -> 清理后覆盖安装
}
return @{ Dir = $destDir; Skip = $false }
}
}
# 部署管线 (本地 / 在线统一使用): 解压自检 -> 整体替换 -> pip 脚本 -> 注册表/PATH -> 完成汇总。
# 返回 $true = 部署成功; $false = 解压/自检失败 (已清理现场, 调用方可换下一个包重试)
function Invoke-DeployPipeline([string]$archiveFilePath, [string]$destDir) {
# 临时文件自动清理: 先清掉历史遗留的临时解压目录 (上次运行异常中断时可能残留)
Get-ChildItem -Path $ExtractParentDir -Filter ".py_deploy_*" -Directory -Force -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
# 迁移清扫: v1.8.1 及之前 SHA256SUMS 清单缓存在脚本目录, 现统一存至 %TEMP%\PyVersions_sums
Get-ChildItem -Path $PSScriptRoot -Filter "SHA256SUMS-*" -File -Force -ErrorAction SilentlyContinue |
Remove-Item -Force -ErrorAction SilentlyContinue
# 解压到临时目录 (不直接覆盖旧目录, 自检通过后再整体替换)
$tempExtract = Join-Path $ExtractParentDir (".py_deploy_" + [guid]::NewGuid().ToString("N").Substring(0, 8))
New-Item -ItemType Directory -Path $tempExtract -Force | Out-Null
Write-Host "正在解压并自检构建 ..."
try {
if (Test-Path $TarExe) {
# Windows 10/11 自带 tar.exe, 可直接解压 .tar.gz
& $TarExe -xzf "$archiveFilePath" -C "$tempExtract"
if ($LASTEXITCODE -ne 0) { throw "tar.exe 解压失败, 退出码 $LASTEXITCODE。" }
} elseif (Test-Path $SevenZipExe) {
& $SevenZipExe x "$archiveFilePath" "-o$tempExtract" -y | Out-Null
if ($LASTEXITCODE -ne 0) { throw "7-Zip 第一阶段 (.gz) 解压失败, 退出码 $LASTEXITCODE。" }
$tarFile = Get-ChildItem -Path $tempExtract -Filter "*.tar" | Select-Object -First 1
if (-not $tarFile) { throw "压缩包内未找到 .tar 文件。" }
& $SevenZipExe x "$($tarFile.FullName)" "-o$tempExtract" -aoa | Out-Null
if ($LASTEXITCODE -ne 0) { throw "7-Zip 第二阶段 (.tar) 解压失败, 退出码 $LASTEXITCODE。" }
} else {
throw "未找到 tar.exe 和 7-Zip ($SevenZipExe), 无法解压。"
}
$tmpPyExe = Join-Path $tempExtract "python\python.exe"
if (-not (Test-Path $tmpPyExe)) { throw "解压后未找到 python.exe。" }
# 构建自检: 标准库 glob/pathlib 必须可导入, 且 sitecustomize 无报错
# (20261110 构建曾在 pip 依赖的 pathlib -> glob 链路上存在缺陷)
$prevEap = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$healthOut = (& $tmpPyExe -c "import glob, pathlib, pip; print('HEALTH_OK')" 2>&1 | Out-String)
$healthCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $prevEap
}
if ($healthCode -ne 0 -or $healthOut -notmatch 'HEALTH_OK' -or $healthOut -match 'Error in sitecustomize' -or $healthOut -match 'ImportError') {
throw "构建自检未通过 (标准库/pip 导入异常), 该构建可能存在缺陷。"
}
Write-Host "构建自检通过!" -ForegroundColor Green
} catch {
Write-Host "[警告] $($_.Exception.Message)" -ForegroundColor Yellow
Remove-Item -Path $tempExtract -Recurse -Force -ErrorAction SilentlyContinue
# 压缩包解压/自检失败: 删除本地文件 (可能是损坏的缓存包), 避免下次继续复用坏包
if (Test-Path $archiveFilePath) { Remove-Item $archiveFilePath -Force -ErrorAction SilentlyContinue }
return $false
}
# 自检通过: 停止占用旧目录的进程 -> 整体替换
$targetPythonExe = Join-Path $destDir "python.exe"
Get-Process -Name "python", "pythonw" -ErrorAction SilentlyContinue |
Where-Object { $_.Path -eq $targetPythonExe } |
ForEach-Object {
Write-Host "正在停止占用该目录的 Python 进程 (PID: $($_.Id))..." -ForegroundColor Yellow
Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
}
# 目标目录的父级链逐层创建 (New-Item -Force 递归补齐缺失层级;
# Move-Item 本身不会创建缺失的父级目录, 不补齐会部署失败)
$destParent = Split-Path -Path $destDir -Parent
if ($destParent -and -not (Test-Path -LiteralPath $destParent)) {
Write-Host "安装目录不存在, 正在逐层创建: $destParent ..."
New-Item -ItemType Directory -Path $destParent -Force | Out-Null
}
if (Test-Path $destDir) {
Write-Host "正在清理旧安装 (覆盖模式) ..."
Remove-Item -Path $destDir -Recurse -Force
} else {
Write-Host "正在安装 ..."
}
Move-Item -Path (Join-Path $tempExtract "python") -Destination $destDir
Remove-Item -Path $tempExtract -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "部署完成: $destDir\" -ForegroundColor Green
Write-Host ""
# 检测已安装的 Python 版本 (供注册表导入与汇总展示使用)
$pyFullVer = ""
try {
$pyFullVer = (& $targetPythonExe -c "import sys; print('.'.join(map(str, sys.version_info[:3])))").Trim()
} catch {}
if ([string]::IsNullOrWhiteSpace($pyFullVer)) {
try { $pyFullVer = (& $targetPythonExe --version) -replace '^Python\s+', '' } catch { $pyFullVer = "" }
}
$pyTag = ""
if ($pyFullVer -match '^([0-9]+\.[0-9]+)') { $pyTag = $Matches[1] }
# ---------- 6. 创建 Scripts\pip 启动脚本 ----------
Write-Banner "6. 正在创建 Scripts\pip 启动脚本 ..."
$scriptsDir = Join-Path $destDir "Scripts"
if (-not (Test-Path $scriptsDir)) {
New-Item -ItemType Directory -Path $scriptsDir -Force | Out-Null
}
# pip.bat: 通用入口; pip3.<minor>.bat (如 pip3.13.bat): 多版本共存时精确指定本版本的 pip (不受 PATH 顺序影响)
$pipBatContent = "@echo off`r`n`"%~dp0..\python.exe`" -m pip %*`r`n"
$batNames = @("pip.bat")
if ($pyTag) { $batNames += "pip$pyTag.bat" }
$batFailed = $false
foreach ($n in $batNames) {
$batPath = Join-Path $scriptsDir $n
Set-Content -Path $batPath -Value $pipBatContent -Encoding Ascii
if (Test-Path $batPath) {
Write-Host "创建成功: $batPath" -ForegroundColor Green
} else {
Write-Host "[错误] $n 创建失败!" -ForegroundColor Red
$batFailed = $true
}
}
if ($batFailed) { return $true }
Write-Host ""
# ---------- 7. 注册表信息与 PATH 环境变量 ----------
Write-Banner "7. 注册表信息与 PATH 环境变量"
$IsAdmin = Test-IsAdmin
if ($IsAdmin) {
Write-Host "当前权限: 管理员 -> 将写入系统级注册表 (HKLM/HKCR) 与系统 PATH" -ForegroundColor Cyan
} else {
Write-Host "当前权限: 普通用户 -> 将写入当前用户注册表 (HKCU, PEP 514 标准) 与用户 PATH" -ForegroundColor Cyan
}
$doRegister = Read-YesNo "是否自动导入注册表信息 (含 .py 文件关联) 并加入 PATH"
if ($doRegister -eq "N") {
Write-Host "已跳过注册表与 PATH 导入。" -ForegroundColor Yellow
} elseif ([string]::IsNullOrWhiteSpace($pyTag)) {
Write-Host "[警告] 无法获取 Python 版本号, 已跳过注册表与 PATH 导入。" -ForegroundColor Yellow
} else {
# ---- 7.1 写入 PythonCore 注册表 (PEP 514, 供 py 启动器/VS Code 等识别) ----
# 仅写入有实际消费者的字段; 不写 PythonPath / Idle / InstalledFeatures 等无消费者的遗留项
$regRoot = if ($IsAdmin) { "HKLM:\SOFTWARE\Python\PythonCore" } else { "HKCU:\Software\Python\PythonCore" }
$tagKey = "$regRoot\$pyTag"
if (Test-Path $tagKey) { Remove-Item -Path $tagKey -Recurse -Force } # 清理旧注册, 防止残留
New-Item -Path $tagKey -Force | Out-Null
Set-ItemProperty -Path $tagKey -Name "DisplayName" -Value "Python $pyTag (64-bit)"
Set-ItemProperty -Path $tagKey -Name "SupportUrl" -Value "https://www.python.org/"
Set-ItemProperty -Path $tagKey -Name "Version" -Value $pyFullVer
Set-ItemProperty -Path $tagKey -Name "SysVersion" -Value $pyTag
Set-ItemProperty -Path $tagKey -Name "SysArchitecture" -Value "64bit"
$installPathKey = "$tagKey\InstallPath"
New-Item -Path $installPathKey -Force | Out-Null
Set-Item -Path $installPathKey -Value "$destDir\"
Set-ItemProperty -Path $installPathKey -Name "ExecutablePath" -Value $targetPythonExe
$pythonwExe = Join-Path $destDir "pythonw.exe"
if (Test-Path $pythonwExe) {
Set-ItemProperty -Path $installPathKey -Name "WindowedExecutablePath" -Value $pythonwExe
}
Write-Host "[成功] PythonCore 注册表已写入: $tagKey (版本 $pyFullVer)" -ForegroundColor Green
# ---- 7.2 文件关联 (.py / .pyw / .pyc) ----
$classRoot = if ($IsAdmin) { "Registry::HKEY_CLASSES_ROOT" } else { "HKCU:\Software\Classes" }
$pyIco = Join-Path $destDir "DLLs\py.ico"
$pycIco = Join-Path $destDir "DLLs\pyc.ico"
# .py -> Python.File
New-Item -Path "$classRoot\.py" -Force | Out-Null
Set-Item -Path "$classRoot\.py" -Value "Python.File"
Set-ItemProperty -Path "$classRoot\.py" -Name "Content Type" -Value "text/plain"
if (Test-Path "$classRoot\Python.File") { Remove-Item -Path "$classRoot\Python.File" -Recurse -Force }
New-Item -Path "$classRoot\Python.File" -Force | Out-Null
Set-Item -Path "$classRoot\Python.File" -Value "Python File"
if (Test-Path $pyIco) {
New-Item -Path "$classRoot\Python.File\DefaultIcon" -Force | Out-Null
Set-Item -Path "$classRoot\Python.File\DefaultIcon" -Value $pyIco
}
New-Item -Path "$classRoot\Python.File\shell\open\command" -Force | Out-Null
Set-Item -Path "$classRoot\Python.File\shell\open\command" -Value "`"$targetPythonExe`" `"%1`" %*"
New-Item -Path "$classRoot\Python.File\shellex\DropHandler" -Force | Out-Null
Set-Item -Path "$classRoot\Python.File\shellex\DropHandler" -Value "{60254CA5-953B-11CF-8C96-00AA00B8708C}"
# .pyc -> Python.CompiledFile
New-Item -Path "$classRoot\.pyc" -Force | Out-Null
Set-Item -Path "$classRoot\.pyc" -Value "Python.CompiledFile"
if (Test-Path "$classRoot\Python.CompiledFile") { Remove-Item -Path "$classRoot\Python.CompiledFile" -Recurse -Force }
New-Item -Path "$classRoot\Python.CompiledFile" -Force | Out-Null
Set-Item -Path "$classRoot\Python.CompiledFile" -Value "Compiled Python File"
if (Test-Path $pycIco) {
New-Item -Path "$classRoot\Python.CompiledFile\DefaultIcon" -Force | Out-Null
Set-Item -Path "$classRoot\Python.CompiledFile\DefaultIcon" -Value $pycIco
}
New-Item -Path "$classRoot\Python.CompiledFile\shell\open\command" -Force | Out-Null
Set-Item -Path "$classRoot\Python.CompiledFile\shell\open\command" -Value "`"$targetPythonExe`" `"%1`" %*"
New-Item -Path "$classRoot\Python.CompiledFile\shellex\DropHandler" -Force | Out-Null
Set-Item -Path "$classRoot\Python.CompiledFile\shellex\DropHandler" -Value "{60254CA5-953B-11CF-8C96-00AA00B8708C}"
# .pyw -> Python.NoConFile
New-Item -Path "$classRoot\.pyw" -Force | Out-Null
Set-Item -Path "$classRoot\.pyw" -Value "Python.NoConFile"
Set-ItemProperty -Path "$classRoot\.pyw" -Name "Content Type" -Value "text/plain"
if (Test-Path "$classRoot\Python.NoConFile") { Remove-Item -Path "$classRoot\Python.NoConFile" -Recurse -Force }
New-Item -Path "$classRoot\Python.NoConFile" -Force | Out-Null
Set-Item -Path "$classRoot\Python.NoConFile" -Value "Python File (no console)"
if (Test-Path $pyIco) {
New-Item -Path "$classRoot\Python.NoConFile\DefaultIcon" -Force | Out-Null
Set-Item -Path "$classRoot\Python.NoConFile\DefaultIcon" -Value $pyIco
}
New-Item -Path "$classRoot\Python.NoConFile\shell\open\command" -Force | Out-Null
Set-Item -Path "$classRoot\Python.NoConFile\shell\open\command" -Value "`"$pythonwExe`" `"%1`" %*"
New-Item -Path "$classRoot\Python.NoConFile\shellex\DropHandler" -Force | Out-Null
Set-Item -Path "$classRoot\Python.NoConFile\shellex\DropHandler" -Value "{60254CA5-953B-11CF-8C96-00AA00B8708C}"
Write-Host "[成功] .py / .pyc / .pyw 文件关联已写入 ($classRoot)" -ForegroundColor Green
# ---- 7.3 加入 PATH 环境变量 (去重后置前, 参考 @Python_Env 脚本逻辑) ----
$envTarget = if ($IsAdmin) { [EnvironmentVariableTarget]::Machine } else { [EnvironmentVariableTarget]::User }
$rawPath = [Environment]::GetEnvironmentVariable("Path", $envTarget)
if (-not $rawPath) { $rawPath = "" }
$entries = @($rawPath -split ";" | Where-Object { $_ -ne "" })
$normalized = @($entries | ForEach-Object { $_.TrimEnd("\").ToLower() })
$toAdd = @()
if ($normalized -notcontains $destDir.ToLower()) { $toAdd += $destDir }
if ($normalized -notcontains $scriptsDir.ToLower()) { $toAdd += $scriptsDir }
if ($toAdd.Count -gt 0) {
$newPath = (@($toAdd) + @($entries)) -join ";"
[Environment]::SetEnvironmentVariable("Path", $newPath, $envTarget)
Write-Host "[成功] 已将以下路径写入 PATH ($envTarget): $($toAdd -join '; ')" -ForegroundColor Green
} else {
Write-Host "[跳过] PATH 中已存在该 Python 路径, 无需重复添加。" -ForegroundColor Yellow
}
Invoke-EnvBroadcast
}
Write-Host ""