-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython_Manager.ps1
More file actions
2741 lines (2365 loc) · 109 KB
/
Copy pathPython_Manager.ps1
File metadata and controls
2741 lines (2365 loc) · 109 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
<#
Python Manager v1.0
Windows 10/11, Windows PowerShell 5.x, PowerShell 7.x
#>
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$Script:ProjectRoot = if (-not [string]::IsNullOrWhiteSpace($PSScriptRoot)) {
$PSScriptRoot
} else {
Split-Path -Parent $MyInvocation.MyCommand.Path
}
#region UI
function Write-Color {
param(
[Parameter(Mandatory = $true)][string]$Text,
[ConsoleColor]$Color = [ConsoleColor]::Gray,
[switch]$NoNewLine
)
if ($NoNewLine) {
Write-Host $Text -ForegroundColor $Color -NoNewline
} else {
Write-Host $Text -ForegroundColor $Color
}
}
function Write-Result {
param(
[ValidateSet('OK', 'WARNING', 'ERROR', 'RUN', 'TIMEOUT', 'CANCELLED')][string]$Status,
[string]$Message
)
$color = [ConsoleColor]::Green
if ($Status -eq 'WARNING') { $color = [ConsoleColor]::Yellow }
if ($Status -eq 'ERROR') { $color = [ConsoleColor]::Red }
if ($Status -eq 'RUN') { $color = [ConsoleColor]::Cyan }
if ($Status -eq 'TIMEOUT') { $color = [ConsoleColor]::Yellow }
if ($Status -eq 'CANCELLED') { $color = [ConsoleColor]::DarkYellow }
Write-Color ("[ {0} ] " -f $Status) $color -NoNewLine
Write-Host $Message
}
function ShowDivider {
param(
[string]$Char = '=',
[ConsoleColor]$Color = [ConsoleColor]::Cyan
)
Write-Color ($Char * 56) $Color
}
function ShowSectionTitle {
param([Parameter(Mandatory = $true)][string]$Text)
Write-Host ''
Write-Color (' ' + $Text) Cyan
Write-Color (' ' + ('-' * $Text.Length)) DarkCyan
Write-Host ''
}
function Write-InfoLine {
param(
[Parameter(Mandatory = $true)][string]$Label,
[object]$Value,
[ConsoleColor]$ValueColor = [ConsoleColor]::Gray
)
Write-Color (' {0,-30}' -f ($Label + ':')) DarkCyan -NoNewLine
Write-Color (Format-Value $Value) $ValueColor
}
function Write-StatusLine {
param(
[Parameter(Mandatory = $true)][string]$Label,
[Parameter(Mandatory = $true)][string]$Status,
[string]$Location,
[ConsoleColor]$StatusColor = [ConsoleColor]::Gray
)
Write-Color (' {0,-18}' -f ($Label + ':')) DarkCyan -NoNewLine
Write-Color ('{0,-14}' -f (Format-Value $Status)) $StatusColor -NoNewLine
Write-Color (Format-Value $Location) Gray
}
function Write-MenuItem {
param(
[Parameter(Mandatory = $true)][string]$Number,
[Parameter(Mandatory = $true)][string]$Title,
[string]$Description
)
Write-Color ('[{0}] ' -f $Number) Yellow -NoNewLine
Write-Color $Title White
if (-not [string]::IsNullOrWhiteSpace($Description)) {
Write-Color (' ' + $Description) DarkGray
}
Write-Host ''
}
function Get-StateColor {
param([string]$Value)
if ($Value -eq 'OK') { return [ConsoleColor]::Green }
if ($Value -eq 'ERROR') { return [ConsoleColor]::Red }
if ($Value -eq 'RUN') { return [ConsoleColor]::Cyan }
if ($Value -eq 'TIMEOUT') { return [ConsoleColor]::Yellow }
if ($Value -eq 'CANCELLED') { return [ConsoleColor]::DarkYellow }
if ($Value -like 'WARNING*') { return [ConsoleColor]::Yellow }
return [ConsoleColor]::Gray
}
function Pause {
Write-Host ''
Write-Color 'Нажмите Enter для продолжения...' DarkGray -NoNewLine
[void][Console]::ReadLine()
}
function ShowHeader {
Clear-Host
ShowDivider '=' Cyan
Write-Color ' Python Manager v1.0' Yellow
ShowDivider '=' Cyan
Write-Host ''
}
function Format-Value {
param([object]$Value)
if ($null -eq $Value) { return 'Не найдено' }
if ([string]::IsNullOrWhiteSpace([string]$Value)) { return 'Не найдено' }
return [string]$Value
}
function Get-VenvStatusText {
param([Parameter(Mandatory = $true)][object]$Venv)
if ($Venv.Healthy) { return 'OK' }
if ($Venv.Exists) { return 'WARNING - требуется пересоздание' }
return 'ERROR - требуется создание'
}
function Show-BrokenVenvExplanation {
param(
[Parameter(Mandatory = $true)][object]$Venv,
[string]$Context = 'Install'
)
Write-Result 'WARNING' 'Обнаружено поврежденное или перенесенное виртуальное окружение.'
Write-Host ''
Write-Color ' Причина:' Cyan
if ($Venv.Exists) {
Write-Color ' venv был создан с Python, которого нет на этом компьютере.' Gray
if (-not [string]::IsNullOrWhiteSpace($Venv.Home)) {
Write-InfoLine 'Старый Python' $Venv.Home
}
if (-not [string]::IsNullOrWhiteSpace($Venv.Executable)) {
Write-InfoLine 'Старый executable' $Venv.Executable
}
} else {
Write-Color ' Папка project venv отсутствует.' Gray
}
Write-Host ''
Write-Color ' Что делать:' Cyan
Write-Color ' Пересоздать только папку venv на основе рабочего Python этого компьютера.' Gray
Write-Color ' Системный Python и файлы проекта удалять не нужно.' Gray
Write-Color ' После успешного пересоздания venv можно установить зависимости проекта.' Gray
Write-Color ' До исправления venv установка зависимостей не должна начинаться.' Gray
if ($Context -eq 'FirstRun') {
Write-Color ' Мастер сначала покажет план, а изменения выполнит только после подтверждения.' DarkGray
}
}
function ShowStatus {
$python = FindPython
$pip = FindPip
$pyLauncher = FindPyLauncher
$winget = FindWinget
$pathInfo = FindPath
$venv = FindVenv
$internet = Test-Internet
$admin = Test-Administrator
ShowSectionTitle 'Система'
Write-InfoLine 'Windows' ([Environment]::OSVersion.VersionString)
Write-InfoLine 'OS architecture' ([Runtime.InteropServices.RuntimeInformation]::OSArchitecture)
Write-InfoLine 'Process architecture' ([Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture)
Write-InfoLine 'PowerShell' $PSVersionTable.PSVersion
ShowSectionTitle 'Основной Python'
Write-InfoLine 'Версия' $python.DefaultVersion
Write-InfoLine 'Полный путь' $python.DefaultPath
Write-InfoLine 'Тип' $python.DefaultType
Write-InfoLine 'Источник' $python.DefaultSource
Write-InfoLine 'Причина выбора' $python.DefaultReason
ShowSectionTitle 'Pip'
Write-InfoLine 'Версия' $pip.Version
Write-InfoLine 'Команда' $pip.Path
Write-InfoLine 'Python для pip' $pip.PythonPath
ShowSectionTitle 'Py Launcher'
Write-InfoLine 'Полный путь' $pyLauncher.Path
ShowSectionTitle 'Найденные версии Python'
Write-InfoLine 'Количество' $python.All.Count Yellow
Write-Color ' Список найденных версий:' DarkCyan
if ($python.All.Count -eq 0) {
Write-Color ' Не найдено' Red
} else {
foreach ($item in $python.All) {
Write-Color (' {0,-12}' -f (Format-Value $item.Version)) Green -NoNewLine
Write-Color ('{0} [{1}; {2}]' -f (Format-Value $item.Path), (Format-Value $item.Type), (Format-Value $item.Source)) Gray
if (-not $item.IsUsable -or $item.IsVenv -or $item.IsStoreAlias) {
Write-Color (' reason: {0}' -f (Format-Value $item.Reason)) DarkGray
}
}
}
ShowSectionTitle 'Системное состояние'
$wingetState = Format-Bool $winget.Found
$internetState = Format-Bool $internet
$adminState = Format-Bool $admin
$venvState = if ($venv.Exists -and -not $venv.Healthy) { 'WARNING' } else { Format-Bool $venv.Available }
$userName = [Environment]::UserName
Write-StatusLine 'Winget' $wingetState $winget.Path (Get-StateColor $wingetState)
Write-StatusLine 'Internet' $internetState 'python.org, pypi.org, files.pythonhosted.org' (Get-StateColor $internetState)
Write-StatusLine 'Administrator' $adminState $userName (Get-StateColor $adminState)
Write-StatusLine 'PATH' $pathInfo.Status 'User: HKCU:\Environment\Path' (Get-StateColor $pathInfo.Status)
Write-Color ' PATH Machine: ' DarkCyan -NoNewLine
Write-Color 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path' Gray
Write-Color ' PATH Process: ' DarkCyan -NoNewLine
Write-Color 'Текущий процесс PowerShell/CMD; участвует в поиске Python' Gray
$venvLocation = $venv.DefaultPath
if ($venv.Exists -and -not $venv.Healthy) { $venvLocation = 'требуется пересоздание project venv' }
Write-StatusLine 'venv' $venvState $venvLocation (Get-StateColor $venvState)
Write-Host ''
ShowDivider '=' Cyan
Write-Host ''
}
function ShowMenu {
Write-Color ' Главное меню' Cyan
Write-Color ' -----------' DarkCyan
Write-Host ''
Write-MenuItem '1' 'Первый запуск на новом ПК' 'Пошаговая диагностика Python, venv и зависимостей проекта.'
Write-MenuItem '2' 'Проверка' 'Диагностика без изменений системы.'
Write-MenuItem '3' 'Обслуживание' 'Backup, очистка, обновление pip и финальная проверка.'
Write-MenuItem '4' 'Зависимости' 'Пакеты pip, requirements.txt и виртуальные окружения.'
Write-MenuItem '5' 'Переустановка Python' 'Отдельное действие на случай проблем с установленным Python.'
Write-MenuItem '0' 'Выход' 'Закрыть Python Manager.'
Write-Color 'Выбор: ' Yellow -NoNewLine
return [Console]::ReadLine()
}
function ShowDependencyMenu {
ShowHeader
Write-Color ' Зависимости Python' Cyan
Write-Color ' ------------------' DarkCyan
Write-Host ''
Write-Color ' Здесь находятся действия с pip-пакетами и окружениями проекта.' Gray
Write-Color ' Если вы не уверены, сначала сделайте Backup, потом обновляйте или восстанавливайте.' Gray
ShowDependencyStatus
ShowLearningLibrariesStatus
Write-Host ''
Write-MenuItem '1' 'Обновить установленные пакеты' 'Проверяет pip-пакеты и обновляет устаревшие версии.'
Write-MenuItem '2' 'Список пакетов для сохранения (Backup)' 'Показывает текущие пакеты через pip freeze. Систему не меняет.'
Write-MenuItem '3' 'Восстановить пакеты из requirements.txt (Restore)' 'Устанавливает пакеты из файла requirements.txt.'
Write-MenuItem '4' 'Виртуальное окружение проекта (venv)' 'Отдельная папка с пакетами для проекта, без смешивания с системным Python.'
Write-MenuItem '5' 'Установить Python в PATH' 'Добавляет python.exe и Scripts, чтобы команды python и pip работали из консоли.'
Write-MenuItem '6' 'Учебные библиотеки' 'Requests, Flask, Telegram Bot API и PyQt6: статус и установка в venv.'
Write-MenuItem '0' 'Назад' 'Вернуться в главное меню.'
Write-Color 'Выбор: ' Yellow -NoNewLine
return [Console]::ReadLine()
}
function ShowLearningLibrariesMenu {
ShowHeader
Write-Color ' Учебные библиотеки Python' Cyan
Write-Color ' -------------------------' DarkCyan
Write-Host ''
Write-Color ' Эти библиотеки не входят в стандартный Python.' Gray
Write-Color ' Менеджер проверяет и устанавливает их в проектное виртуальное окружение venv.' Gray
Write-Color ' Если venv ещё нет, он будет создан перед установкой.' Gray
ShowLearningLibrariesStatus
Write-Host ''
Write-MenuItem '1' 'Установить Requests' 'Запросы в интернет, HTTP и работа с API.'
Write-MenuItem '2' 'Установить Flask' 'Мини-фреймворк для создания веб-сайтов и API.'
Write-MenuItem '3' 'Установить Telegram Bot API' 'Пакет python-telegram-bot для разработки Telegram-ботов.'
Write-MenuItem '4' 'Установить PyQt6' 'Библиотека для создания desktop-приложений с графическим интерфейсом.'
Write-MenuItem '5' 'Установить все' 'Поставить все учебные библиотеки в venv.'
Write-MenuItem '0' 'Назад' 'Вернуться в меню зависимостей.'
Write-Color 'Выбор: ' Yellow -NoNewLine
return [Console]::ReadLine()
}
function ShowVenvMenu {
ShowHeader
Write-Color ' Виртуальное окружение проекта (venv)' Cyan
Write-Color ' -----------------------------------' DarkCyan
Write-Host ''
Write-Color ' venv - это отдельная папка Python для проекта.' Gray
Write-Color ' Пакеты внутри venv не засоряют основной Python Windows.' Gray
Write-Color ' Обычный порядок: создать venv, затем импортировать requirements.txt или ставить пакеты pip.' Gray
Write-Color ' Активация в PowerShell: .\venv\Scripts\Activate.ps1' DarkGray
Write-Color ' Если запуск скриптов запрещён: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned' DarkGray
ShowVenvStatus
Write-Host ''
Write-MenuItem '1' 'Создать venv' 'Создаёт отдельное окружение в текущей папке или по указанному пути.'
Write-MenuItem '2' 'Удалить venv' 'Удаляет только папку виртуального окружения. Основной Python не трогает.'
Write-MenuItem '3' 'Сохранить список пакетов в requirements.txt' 'Записывает установленные пакеты в файл requirements.txt.'
Write-MenuItem '4' 'Установить пакеты из requirements.txt' 'Ставит пакеты из requirements.txt через pip install -r.'
Write-MenuItem '0' 'Назад' 'Вернуться в меню зависимостей.'
Write-Color 'Выбор: ' Yellow -NoNewLine
return [Console]::ReadLine()
}
#endregion
#region Detection
function Format-Bool {
param([bool]$Value)
if ($Value) { return 'OK' }
return 'ERROR'
}
function ConvertTo-CleanOutput {
param([object[]]$Output)
$clean = New-Object System.Collections.Generic.List[string]
foreach ($line in @($Output)) {
$text = [string]$line
if ([string]::IsNullOrWhiteSpace($text)) { continue }
$text = $text -replace '[\u0000-\u001F\u007F-\u009F]', ''
$text = $text -replace '[\u2580-\u259F\u2800-\u28FF]', ''
$text = $text.Trim()
if ([string]::IsNullOrWhiteSpace($text)) { continue }
if ($text -match '^[\|\-\\\/\s]+$') { continue }
[void]$clean.Add($text)
}
return $clean.ToArray()
}
function Get-FriendlyWingetError {
param([object[]]$Output)
$clean = @(ConvertTo-CleanOutput -Output $Output)
if ($clean.Count -eq 0) {
return 'winget завершился с ошибкой, но не вернул читаемое сообщение.'
}
foreach ($line in $clean) {
if ($line -match 'No applicable|No package|not found|already installed|newer version|failed|error|0x[0-9A-Fa-f]+') {
return $line
}
}
return ($clean | Select-Object -Last 1)
}
function Format-Elapsed {
param([TimeSpan]$Duration)
if ($Duration.TotalHours -ge 1) { return $Duration.ToString('hh\:mm\:ss') }
return $Duration.ToString('mm\:ss')
}
function ConvertTo-NativeArgumentString {
param([string[]]$Arguments = @())
$quoted = New-Object System.Collections.Generic.List[string]
foreach ($arg in $Arguments) {
if ($null -eq $arg) { continue }
$text = [string]$arg
if ($text -match '[\s"]') {
$text = '"' + ($text -replace '"', '\"') + '"'
}
[void]$quoted.Add($text)
}
return ($quoted -join ' ')
}
function Stop-ProcessTreeSafe {
param([Parameter(Mandatory = $true)][int]$ProcessId)
try {
$children = @(Get-CimInstance Win32_Process -Filter ("ParentProcessId={0}" -f $ProcessId) -ErrorAction SilentlyContinue)
} catch {
$children = @()
try { $children = @(Get-WmiObject Win32_Process -Filter ("ParentProcessId={0}" -f $ProcessId) -ErrorAction SilentlyContinue) } catch {}
}
foreach ($child in $children) {
Stop-ProcessTreeSafe -ProcessId ([int]$child.ProcessId)
}
try {
$target = Get-Process -Id $ProcessId -ErrorAction Stop
if (-not $target.HasExited) { Stop-Process -Id $ProcessId -Force -ErrorAction Stop }
} catch {
}
}
function Invoke-Native {
param(
[Parameter(Mandatory = $true)][string]$FilePath,
[string[]]$Arguments = @(),
[string]$OperationName,
[int]$TimeoutSeconds = 0,
[int]$HeartbeatSeconds = 15,
[switch]$Quiet
)
$output = @()
$stdout = @()
$stderr = @()
$exitCode = 1
$status = 'ERROR'
$timedOut = $false
$duration = [TimeSpan]::Zero
try {
$stopwatch = [Diagnostics.Stopwatch]::StartNew()
$process = New-Object Diagnostics.Process
$process.StartInfo = New-Object Diagnostics.ProcessStartInfo
$process.StartInfo.FileName = $FilePath
$process.StartInfo.Arguments = ConvertTo-NativeArgumentString -Arguments $Arguments
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.StartInfo.CreateNoWindow = $true
if (-not $Quiet) {
$name = if ([string]::IsNullOrWhiteSpace($OperationName)) { (Split-Path -Leaf $FilePath) } else { $OperationName }
Write-Result 'RUN' $name
}
[void]$process.Start()
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
$nextHeartbeat = [Math]::Max(1, $HeartbeatSeconds)
while (-not $process.WaitForExit(1000)) {
$elapsedSeconds = [int][Math]::Floor($stopwatch.Elapsed.TotalSeconds)
if ($TimeoutSeconds -gt 0 -and $elapsedSeconds -ge $TimeoutSeconds) {
$timedOut = $true
Stop-ProcessTreeSafe -ProcessId $process.Id
break
}
if (-not $Quiet -and $elapsedSeconds -ge $nextHeartbeat) {
$name = if ([string]::IsNullOrWhiteSpace($OperationName)) { (Split-Path -Leaf $FilePath) } else { $OperationName }
Write-Color (' [{0}] {1}: процесс выполняется...' -f (Format-Elapsed $stopwatch.Elapsed), $name) Cyan
$nextHeartbeat += [Math]::Max(1, $HeartbeatSeconds)
}
}
if ($timedOut) {
[void]$process.WaitForExit(5000)
} else {
$process.WaitForExit()
}
$stopwatch.Stop()
$duration = $stopwatch.Elapsed
$stdoutText = ''
$stderrText = ''
try {
if ($stdoutTask.Wait(1000)) { $stdoutText = $stdoutTask.Result }
} catch {}
try {
if ($stderrTask.Wait(1000)) { $stderrText = $stderrTask.Result }
} catch {}
if (-not [string]::IsNullOrEmpty($stdoutText)) { $stdout = @($stdoutText -split "`r?`n" | Where-Object { $_ -ne '' }) }
if (-not [string]::IsNullOrEmpty($stderrText)) { $stderr = @($stderrText -split "`r?`n" | Where-Object { $_ -ne '' }) }
$output = @($stdout + $stderr)
$exitCode = if ($timedOut) { -1 } else { $process.ExitCode }
if ($timedOut) {
$status = 'TIMEOUT'
} elseif ($exitCode -eq 0) {
$status = 'SUCCESS'
} else {
$status = 'ERROR'
}
if (-not $Quiet -and ($status -eq 'TIMEOUT')) {
Write-Result 'TIMEOUT' ('{0} остановлен по timeout {1} сек.' -f $OperationName, $TimeoutSeconds)
}
} catch {
$output = @($_.Exception.Message)
$stderr = @($_.Exception.Message)
$exitCode = 1
$status = 'ERROR'
}
return [pscustomobject]@{
ExitCode = $exitCode
Output = @($output | ForEach-Object { [string]$_ })
StdOut = @($stdout | ForEach-Object { [string]$_ })
StdErr = @($stderr | ForEach-Object { [string]$_ })
Success = ($exitCode -eq 0)
Status = $status
TimedOut = $timedOut
Duration = $duration
}
}
function Get-CommandPath {
param([Parameter(Mandatory = $true)][string]$Name)
try {
$command = Get-Command $Name -ErrorAction Stop | Select-Object -First 1
return $command.Source
} catch {
return $null
}
}
function Get-ObjectPropertyValue {
param(
[Parameter(Mandatory = $true)][object]$Object,
[Parameter(Mandatory = $true)][string]$Name
)
$property = $Object.PSObject.Properties[$Name]
if ($null -eq $property) { return $null }
return $property.Value
}
function Test-PathSafe {
param(
[string]$Path,
[switch]$Literal
)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
try {
if ($Literal) { return (Test-Path -LiteralPath $Path -ErrorAction Stop) }
return (Test-Path $Path -ErrorAction Stop)
} catch {
return $false
}
}
function Get-PythonVersionFromExecutable {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-PathSafe -Path $Path -Literal)) { return $null }
$result = Invoke-Native -FilePath $Path -Arguments @('--version') -Quiet -TimeoutSeconds 10
$text = ($result.Output -join ' ').Trim()
if ($text -match 'Python\s+([0-9]+(\.[0-9]+){1,3})') { return $matches[1] }
return $null
}
function Normalize-PythonVersion {
param([string]$Version)
if ([string]::IsNullOrWhiteSpace($Version)) { return $null }
$text = $Version.Trim()
if ($text -match '^([0-9]+)\.([0-9]+)\.([0-9]+)(?:\.([0-9]+))?$') {
$major = [int]$matches[1]
$minor = [int]$matches[2]
$patch = [int]$matches[3]
if ($patch -ge 1000) {
$patch = [int][Math]::Floor($patch / 1000)
}
return ('{0}.{1}.{2}' -f $major, $minor, $patch)
}
return $text
}
function Get-PythonVersionFromText {
param([string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return $null }
if ($Text -match 'Python\s+([0-9]+(\.[0-9]+){1,3})') {
return (Normalize-PythonVersion $matches[1])
}
if ($Text -match '([0-9]+(\.[0-9]+){1,3})') {
return (Normalize-PythonVersion $matches[1])
}
return $null
}
function Get-VersionKey {
param([string]$Version)
$normalized = Normalize-PythonVersion $Version
if ([string]::IsNullOrWhiteSpace($normalized)) { return [version]'0.0' }
try { return [version]$normalized } catch { return [version]'0.0' }
}
function Get-PathEntries {
$entries = New-Object System.Collections.Generic.List[string]
foreach ($scope in @('Machine', 'User', 'Process')) {
$value = [Environment]::GetEnvironmentVariable('Path', $scope)
if (-not [string]::IsNullOrWhiteSpace($value)) {
foreach ($entry in ($value -split ';')) {
if (-not [string]::IsNullOrWhiteSpace($entry)) {
$expanded = [Environment]::ExpandEnvironmentVariables($entry.Trim())
if (-not [string]::IsNullOrWhiteSpace($expanded) -and -not $entries.Contains($expanded)) {
[void]$entries.Add($expanded)
}
}
}
}
}
return $entries.ToArray()
}
function Get-PythonRuntimeInfo {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-PathSafe -Path $Path -Literal)) { return $null }
$code = 'import sys,platform; print("executable="+sys.executable); print("prefix="+sys.prefix); print("base_prefix="+getattr(sys,"base_prefix",sys.prefix)); print("arch="+platform.machine())'
$result = Invoke-Native -FilePath $Path -Arguments @('-c', $code) -Quiet -TimeoutSeconds 10
if (-not $result.Success) { return $null }
$map = @{}
foreach ($line in $result.Output) {
if ($line -match '^([^=]+)=(.*)$') { $map[$matches[1]] = $matches[2] }
}
return [pscustomobject]@{
Executable = $map['executable']
Prefix = $map['prefix']
BasePrefix = $map['base_prefix']
Architecture = $map['arch']
}
}
function Get-PythonCandidate {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Source
)
if (-not (Test-PathSafe -Path $Path -Literal)) { return $null }
$resolved = (Resolve-Path -LiteralPath $Path).Path
$lowerPath = $resolved.ToLowerInvariant()
$projectVenvPath = (Join-Path $Script:ProjectRoot 'venv\Scripts\python.exe').ToLowerInvariant()
$isStoreAlias = ($lowerPath -like '*\microsoft\windowsapps\python*.exe')
$version = $null
$runtime = $null
if (-not $isStoreAlias) {
$version = Get-PythonVersionFromExecutable -Path $resolved
$runtime = Get-PythonRuntimeInfo -Path $resolved
}
$isVenvByPath = ($lowerPath -like '*\venv\scripts\python.exe') -or ($lowerPath -like '*\.venv\scripts\python.exe')
$isVenvByRuntime = $false
if ($runtime -and -not [string]::IsNullOrWhiteSpace($runtime.Prefix) -and -not [string]::IsNullOrWhiteSpace($runtime.BasePrefix)) {
$isVenvByRuntime = ($runtime.Prefix -ne $runtime.BasePrefix)
}
$isVenv = $isVenvByPath -or $isVenvByRuntime
$isProjectVenv = ($lowerPath -eq $projectVenvPath)
$isThirdPartyVenv = ($isVenv -and -not $isProjectVenv)
$type = 'Unknown'
$usable = $false
$reason = 'Кандидат не выбран автоматически.'
if ($isStoreAlias) {
$type = 'Microsoft Store alias'
$reason = 'Store alias не считается установленным CPython.'
} elseif ($isProjectVenv) {
$type = 'Project venv'
$reason = 'Проектный venv не используется как основной системный Python.'
} elseif ($isThirdPartyVenv) {
$type = 'Third-party venv'
$reason = 'Сторонний venv не используется как основной системный Python.'
} elseif ($Source -eq 'Registry') {
$type = 'Installed CPython'
$usable = (-not [string]::IsNullOrWhiteSpace($version))
$reason = 'Установленный CPython из registry.'
} elseif ($Source -eq 'PyLauncher') {
$type = 'Py launcher target'
$usable = (-not [string]::IsNullOrWhiteSpace($version))
$reason = 'Цель py launcher после проверки executable.'
} elseif ($Source -eq 'PATH' -or $Source -eq 'Default') {
$type = 'PATH CPython'
$usable = (-not [string]::IsNullOrWhiteSpace($version))
$reason = 'CPython из PATH после исключения venv и alias.'
} else {
$usable = (-not [string]::IsNullOrWhiteSpace($version))
}
return [pscustomobject]@{
Version = (Normalize-PythonVersion $version)
Path = $resolved
Source = $Source
Type = $type
Architecture = $(if ($runtime) { $runtime.Architecture } else { $null })
IsVenv = $isVenv
IsProjectVenv = $isProjectVenv
IsThirdPartyVenv = $isThirdPartyVenv
IsStoreAlias = $isStoreAlias
IsUsable = $usable
Reason = $reason
}
}
function FindPythonInRegistry {
$items = New-Object System.Collections.Generic.List[object]
$roots = @(
'HKLM:\SOFTWARE\Python\PythonCore',
'HKLM:\SOFTWARE\WOW6432Node\Python\PythonCore',
'HKCU:\SOFTWARE\Python\PythonCore'
)
foreach ($root in $roots) {
if (-not (Test-PathSafe -Path $root)) { continue }
foreach ($versionKey in (Get-ChildItem $root -ErrorAction SilentlyContinue)) {
$installPathKey = Join-Path $versionKey.PSPath 'InstallPath'
if (-not (Test-PathSafe -Path $installPathKey)) { continue }
try {
$installPathItem = Get-Item -Path $installPathKey -ErrorAction Stop
$installPath = $installPathItem.GetValue('')
if ([string]::IsNullOrWhiteSpace($installPath)) { $installPath = $installPathItem.GetValue('InstallPath') }
if (-not [string]::IsNullOrWhiteSpace($installPath)) {
$exe = Join-Path $installPath 'python.exe'
if (Test-PathSafe -Path $exe -Literal) {
[void]$items.Add([pscustomobject]@{
Version = $versionKey.PSChildName
Path = (Resolve-Path -LiteralPath $exe).Path
Source = 'Registry'
})
}
}
} catch {
}
}
}
return $items.ToArray()
}
function FindPythonInPath {
$items = New-Object System.Collections.Generic.List[object]
foreach ($entry in (Get-PathEntries)) {
foreach ($name in @('python.exe', 'python3.exe')) {
$candidate = Join-Path $entry $name
if (Test-PathSafe -Path $candidate -Literal) {
$resolved = (Resolve-Path -LiteralPath $candidate).Path
[void]$items.Add([pscustomobject]@{
Path = $resolved
Source = 'PATH'
})
}
}
}
return $items.ToArray()
}
function FindPythonWithPyLauncher {
$items = New-Object System.Collections.Generic.List[object]
$py = FindPyLauncher
if (-not $py.Found) { return $items.ToArray() }
$result = Invoke-Native -FilePath $py.Path -Arguments @('-0p') -Quiet -TimeoutSeconds 10
if (-not $result.Success) { return $items.ToArray() }
foreach ($line in $result.Output) {
if ($line -match '((?:[A-Za-z]:|\\\\)[^\r\n]*?python(?:3)?\.exe)') {
[void]$items.Add([pscustomobject]@{
Version = $null
Path = $matches[1].Trim()
Source = 'PyLauncher'
})
}
}
return $items.ToArray()
}
function FindPython {
$items = New-Object System.Collections.Generic.List[object]
foreach ($item in (FindPythonInRegistry)) { [void]$items.Add($item) }
foreach ($item in (FindPythonWithPyLauncher)) { [void]$items.Add($item) }
foreach ($item in (FindPythonInPath)) { [void]$items.Add($item) }
$defaultPath = Get-CommandPath 'python.exe'
if ($defaultPath) {
[void]$items.Add([pscustomobject]@{
Path = $defaultPath
Source = 'Default'
})
}
$sourcePriority = @{
Registry = 0
PyLauncher = 1
PATH = 2
Default = 3
}
$preferredByPath = @{}
foreach ($item in @($items | Where-Object { -not [string]::IsNullOrWhiteSpace($_.Path) })) {
try {
$resolvedKey = (Resolve-Path -LiteralPath $item.Path -ErrorAction Stop).Path.ToLowerInvariant()
} catch {
$resolvedKey = $item.Path.ToLowerInvariant()
}
$newPriority = if ($sourcePriority.ContainsKey($item.Source)) { $sourcePriority[$item.Source] } else { 9 }
if (-not $preferredByPath.ContainsKey($resolvedKey)) {
$preferredByPath[$resolvedKey] = $item
} else {
$old = $preferredByPath[$resolvedKey]
$oldPriority = if ($sourcePriority.ContainsKey($old.Source)) { $sourcePriority[$old.Source] } else { 9 }
if ($newPriority -lt $oldPriority) { $preferredByPath[$resolvedKey] = $item }
}
}
$preferredItems = @($preferredByPath.Values)
$candidates = New-Object System.Collections.Generic.List[object]
foreach ($item in $preferredItems) {
$candidate = Get-PythonCandidate -Path $item.Path -Source $item.Source
if ($candidate) { [void]$candidates.Add($candidate) }
}
$unique = @($candidates.ToArray() | Sort-Object Path -Unique)
$default = $null
$usable = @($unique | Where-Object { $_.IsUsable })
if ($usable.Count -gt 0) {
$default = $usable | Sort-Object `
@{Expression = { if ($_.Source -eq 'Registry') { 0 } elseif ($_.Source -eq 'PyLauncher') { 1 } elseif ($_.Source -eq 'PATH') { 2 } elseif ($_.Source -eq 'Default') { 3 } else { 9 } }; Ascending = $true }, `
@{Expression = { Get-VersionKey $_.Version }; Descending = $true }, `
Path | Select-Object -First 1
}
return [pscustomobject]@{
DefaultPath = $(if ($default) { $default.Path } else { $null })
DefaultVersion = $(if ($default) { $default.Version } else { $null })
DefaultType = $(if ($default) { $default.Type } else { $null })
DefaultSource = $(if ($default) { $default.Source } else { $null })
DefaultReason = $(if ($default) { $default.Reason } else { $null })
All = @($unique | Sort-Object @{Expression = { Get-VersionKey $_.Version }; Descending = $true }, Path)
}
}
function FindPip {
$python = FindPython
$pipPath = $null
$version = $null
$pythonPath = $python.DefaultPath
if ($pythonPath) {
$result = Invoke-Native -FilePath $pythonPath -Arguments @('-m', 'pip', '--version') -Quiet -TimeoutSeconds 20
$text = ($result.Output -join ' ').Trim()
if ($text -match 'pip\s+([^\s]+)') { $version = $matches[1] }
if ($result.Success) { $pipPath = ('"{0}" -m pip' -f $pythonPath) }
}
return [pscustomobject]@{
Path = $pipPath
Version = $version
PythonPath = $pythonPath
}
}
function FindPyLauncher {
$path = Get-CommandPath 'py.exe'
return [pscustomobject]@{ Path = $path; Found = ($null -ne $path) }
}
function FindWinget {
$path = Get-CommandPath 'winget.exe'
return [pscustomobject]@{ Path = $path; Found = ($null -ne $path) }
}
function FindPath {
$allEntries = @()
foreach ($scope in @('Machine', 'User', 'Process')) {
$value = [Environment]::GetEnvironmentVariable('Path', $scope)
if ([string]::IsNullOrWhiteSpace($value)) { continue }
foreach ($entry in ($value -split ';')) {
$trimmed = $entry.Trim()
if ([string]::IsNullOrWhiteSpace($trimmed)) { continue }
$expanded = [Environment]::ExpandEnvironmentVariables($trimmed)
$exists = Test-PathSafe -Path $expanded -Literal
$allEntries += [pscustomobject]@{
Scope = $scope
Raw = $trimmed
Expanded = $expanded
Exists = $exists
}
}
}
$broken = @($allEntries | Where-Object { -not $_.Exists })
$status = 'OK'
if ($broken.Count -gt 0) { $status = ('WARNING ({0} битых записей)' -f $broken.Count) }
return [pscustomobject]@{
Status = $status
Entries = @($allEntries)
Broken = @($broken)
}
}
function Get-VenvHealth {
param([Parameter(Mandatory = $true)][string]$VenvPath)
$pyvenvCfg = Join-Path $VenvPath 'pyvenv.cfg'
$venvPython = Get-VenvPythonPath -VenvPath $VenvPath
$exists = Test-PathSafe -Path $VenvPath -Literal
$ready = $exists -and (Test-PathSafe -Path $pyvenvCfg -Literal) -and (Test-PathSafe -Path $venvPython -Literal)
$healthy = $ready
$reason = if ($exists) { 'venv найден.' } else { 'venv не найден.' }
$venvHome = $null
$executable = $null
if ($exists -and -not $ready) {
$healthy = $false
$reason = 'Папка venv есть, но pyvenv.cfg или Scripts\python.exe отсутствует.'
}
if ($ready) {
try {
foreach ($line in (Get-Content -LiteralPath $pyvenvCfg -ErrorAction Stop)) {
if ($line -match '^home\s*=\s*(.+)$') { $venvHome = $matches[1].Trim() }
if ($line -match '^executable\s*=\s*(.+)$') { $executable = $matches[1].Trim() }
}
if (-not [string]::IsNullOrWhiteSpace($venvHome) -and -not (Test-PathSafe -Path $venvHome -Literal)) {
$healthy = $false
$reason = ('venv перенесен или поврежден: home не найден ({0}).' -f $venvHome)
} elseif (-not [string]::IsNullOrWhiteSpace($executable) -and -not (Test-PathSafe -Path $executable -Literal)) {
$healthy = $false
$reason = ('venv перенесен или поврежден: executable не найден ({0}).' -f $executable)
} else {
$reason = 'venv выглядит здоровым.'
}
} catch {
$healthy = $false
$reason = $_.Exception.Message
}
}
return [pscustomobject]@{
Exists = $exists
Ready = $ready
Healthy = $healthy
Reason = $reason
Path = $VenvPath
PythonPath = $venvPython
Home = $venvHome
Executable = $executable
}
}
function FindVenv {
$python = FindPython
$available = $false
if ($python.DefaultPath) {
$result = Invoke-Native -FilePath $python.DefaultPath -Arguments @('-m', 'venv', '--help') -Quiet -TimeoutSeconds 20
$available = $result.Success
}
$defaultPath = Join-Path $Script:ProjectRoot 'venv'
$health = Get-VenvHealth -VenvPath $defaultPath
return [pscustomobject]@{
Available = $available
DefaultPath = $defaultPath
Exists = $health.Exists
Ready = $health.Ready
Healthy = $health.Healthy
Reason = $health.Reason
}
}
function Test-Administrator {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
} catch {
return $false
}
}
function Test-Internet {
$targets = @(
'https://www.python.org/',
'https://pypi.org/',
'https://files.pythonhosted.org/'