fix: harden powershell environment scripts
This commit is contained in:
+63
-4
@@ -1,8 +1,67 @@
|
||||
param(
|
||||
[int]$Port = 7001,
|
||||
[string]$HostAddress = "0.0.0.0",
|
||||
[switch]$NoPause
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$VenvPython = Join-Path $Root ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $VenvPython)) {
|
||||
throw "未找到虚拟环境。请先运行 scripts\install_offline.ps1。"
|
||||
$InstallScript = Join-Path $PSScriptRoot "install_offline.ps1"
|
||||
|
||||
function Wait-BeforeExit {
|
||||
if (-not $NoPause) {
|
||||
Write-Host ""
|
||||
Read-Host "Press Enter to exit"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-PortAvailable {
|
||||
param([int]$CheckPort)
|
||||
$listener = Get-NetTCPConnection -LocalPort $CheckPort -State Listen -ErrorAction SilentlyContinue
|
||||
if ($listener) {
|
||||
$pids = ($listener | Select-Object -ExpandProperty OwningProcess -Unique) -join ", "
|
||||
throw "Port $CheckPort is already in use. Owning process PID: $pids"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-EnvironmentReady {
|
||||
if (-not (Test-Path $VenvPython)) {
|
||||
return $false
|
||||
}
|
||||
& $VenvPython -c "import fastapi, uvicorn, xlrd, xlwt, xlutils, httpx, yaml" 2>$null
|
||||
return ($LASTEXITCODE -eq 0)
|
||||
}
|
||||
|
||||
try {
|
||||
Set-Location $Root
|
||||
|
||||
if (-not (Test-EnvironmentReady)) {
|
||||
Write-Host "Runtime environment is missing or incomplete. Installing now..." -ForegroundColor Yellow
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File $InstallScript -NoPause
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Automatic environment installation failed. See the error above."
|
||||
}
|
||||
}
|
||||
|
||||
Test-PortAvailable -CheckPort $Port
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Starting PCFAnalysis service" -ForegroundColor Cyan
|
||||
Write-Host "Bind URL: http://$HostAddress`:$Port"
|
||||
Write-Host "Local URL: http://127.0.0.1`:$Port"
|
||||
Write-Host "Press Ctrl+C in this window to stop the service."
|
||||
Write-Host ""
|
||||
|
||||
& $VenvPython -m uvicorn app.main:app --host $HostAddress --port $Port
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Service exited with code: $LASTEXITCODE"
|
||||
}
|
||||
} catch {
|
||||
Write-Host ""
|
||||
Write-Host "Startup failed:" -ForegroundColor Red
|
||||
Write-Host $_.Exception.Message -ForegroundColor Red
|
||||
exit 1
|
||||
} finally {
|
||||
Wait-BeforeExit
|
||||
}
|
||||
Set-Location $Root
|
||||
& $VenvPython -m uvicorn app.main:app --host 127.0.0.1 --port 7001
|
||||
|
||||
Reference in New Issue
Block a user