$ErrorActionPreference = 'Stop' Set-Location -LiteralPath $PSScriptRoot $env:PYTHONIOENCODING = 'utf-8' $HostAddress = '127.0.0.1' $Port = 8501 $EntryUrl = "http://${HostAddress}:${Port}" $Python = Join-Path $PSScriptRoot '.venv-ui\Scripts\python.exe' function Test-PortInUse { $pattern = ":$Port\s+" netstat -ano | Where-Object { $_ -match $pattern -and $_ -match 'LISTENING' } } function Stop-ExistingUi { $root = $PSScriptRoot $ids = @{} Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^python(\.exe)?$' -and $_.CommandLine -and ($_.CommandLine -match 'streamlit') } | ForEach-Object { $cmd = $_.CommandLine $fromProject = $cmd.IndexOf($root, [StringComparison]::OrdinalIgnoreCase) -ge 0 $genericApp = $cmd -match 'streamlit.*run.*app\.py' if ($fromProject -or $genericApp) { $ids[[int]$_.ProcessId] = $true } } Test-PortInUse | ForEach-Object { if ($_ -match '\s(\d+)\s*$') { $ids[[int]$Matches[1]] = $true } } foreach ($id in @($ids.Keys)) { if ($id -gt 0) { Stop-Process -Id $id -Force -ErrorAction SilentlyContinue } } $deadline = (Get-Date).AddSeconds(10) do { if (-not (Test-PortInUse)) { return } Start-Sleep -Milliseconds 200 } while ((Get-Date) -lt $deadline) throw "端口 $Port 仍被占用,无法启动。" } function Wait-UiReady { param($Process) $deadline = (Get-Date).AddSeconds(90) while ((Get-Date) -lt $deadline) { if ($Process.HasExited) { throw 'Streamlit 进程已退出,启动失败。' } try { $client = New-Object System.Net.Sockets.TcpClient $client.Connect($HostAddress, $Port) $client.Close() return } catch { Start-Sleep -Milliseconds 300 } } throw "等待界面启动超时:$EntryUrl" } function Ensure-UiEnvironment { if (Get-Command uv -ErrorAction SilentlyContinue) { if (-not (Test-Path $Python)) { uv venv .venv-ui --python 3.13 if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' } } uv pip install --python $Python -r requirements-ui.txt if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' } return } if (-not (Test-Path $Python)) { python -m venv .venv-ui if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' } } & $Python -m pip install -r requirements-ui.txt if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' } } Stop-ExistingUi Ensure-UiEnvironment Write-Host '' Write-Host "正在启动 MarketGrid 工具箱" Write-Host "入口地址:$EntryUrl" Write-Host '' $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $Python $psi.Arguments = "-m streamlit run `"$PSScriptRoot\app.py`" --server.headless true --server.address $HostAddress --server.port $Port --browser.serverAddress $HostAddress --browser.gatherUsageStats false" $psi.WorkingDirectory = $PSScriptRoot $psi.UseShellExecute = $false $ui = [System.Diagnostics.Process]::Start($psi) try { Wait-UiReady -Process $ui Write-Host "已启动:$EntryUrl" Start-Process $EntryUrl $ui.WaitForExit() exit $ui.ExitCode } finally { if (-not $ui.HasExited) { Stop-Process -Id $ui.Id -Force -ErrorAction SilentlyContinue } }