Files
pricing_review/release/testdata/panel_server.py

501 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""testdata 控制台(本地网页版,2026-10-09)。
双击「启动testdata.bat」自动打开浏览器:http://127.0.0.1:8412
填参数 → 开始生成 → 实时日志;停止 = 软暂停;删除 = 分块删除全部测试数据;
版本对齐 = 测试库换到别的母体后,把测试批次解析器版本对齐到该母体当前版本。
生成写入独立测试库 history-test.db / session-test.db,真实库零污染。
只在本机 127.0.0.1 监听。不改任何软件代码。
"""
import json
import os
import subprocess
import sys
import time
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import gen_testdata as G # noqa: E402
G._safe_stdio() # GBK 控制台容错(U+200C 等)
PORT = 8412
_state = {"proc": None, "mode": None}
_lock = threading.Lock()
LOG = []
def log(msg):
LOG.append("%s %s" % (__import__("time").strftime("%H:%M:%S"), msg))
if len(LOG) > 2000:
del LOG[:500]
try:
print(msg, flush=True)
except Exception:
pass
def _cfg():
"""读 config.json(找不到/坏档返回空 dict)。"""
try:
with open(G.CFG_PATH, encoding="utf-8") as f:
return json.load(f) or {}
except Exception:
return {}
def running():
p = _state["proc"]
return p is not None and p.poll() is None
def _drain(proc):
try:
for line in iter(proc.stdout.readline, ""):
if not line:
break
log(line.rstrip())
except Exception:
pass
def start_sub(mode, cfg):
with _lock:
if running():
return False, "已有任务在跑,请先停止。"
args = [sys.executable, "-u", os.path.join(HERE, "gen_testdata.py")]
if mode == "run":
cfgpath = os.path.join(HERE, "run_cfg.json")
with open(cfgpath, "w", encoding="utf-8") as f:
json.dump(cfg, f, ensure_ascii=False, indent=2)
args += ["--run", cfgpath]
elif mode == "delete":
args += ["--delete", "--yes"]
else:
return False, "未知操作"
try:
if os.path.exists(G.PAUSE_FLAG):
os.remove(G.PAUSE_FLAG)
except Exception:
pass
proc = subprocess.Popen(args, cwd=HERE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True,
encoding="utf-8", errors="replace")
_state["proc"] = proc
_state["mode"] = mode
threading.Thread(target=_drain, args=(proc,), daemon=True).start()
return True, "已启动:%s" % mode
def stop_sub():
with _lock:
if not running():
return "没有在跑的任务。"
open(G.PAUSE_FLAG, "w").close() # 软暂停:当前份做完即退出
return "已发软暂停信号:当前这一份做完就安全停(不丢已提交进度)。"
class H(BaseHTTPRequestHandler):
def _send(self, code, body, ctype="application/json; charset=utf-8"):
raw = body if isinstance(body, bytes) else json.dumps(
body, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def log_message(self, *a):
pass
def do_GET(self):
if self.path in ("/", "/index.html"):
self._send(200, PAGE.encode("utf-8"), "text/html; charset=utf-8")
elif self.path == "/api/stats":
dd = G.find_data_dir()
try:
s = G.stats_of(dd) if dd else {"data_dir": None}
except Exception as e:
s = {"data_dir": dd, "error": str(e)}
rd = _cfg().get("ref_dir", "")
G.REF_DIR = rd or None
if dd:
rh, th, rs, ts = G.db_paths(dd)
s["ref_dir"] = os.path.dirname(rh)
s["test_dir"] = dd
s["ref_names"] = [os.path.basename(rh), os.path.basename(rs)]
s["test_names"] = [os.path.basename(th), os.path.basename(ts)]
s["ref_ok"] = [os.path.exists(rh), os.path.exists(rs)]
s["test_ok"] = [os.path.exists(th), os.path.exists(ts)]
s["running"] = running()
if dd and "error" not in s:
try:
s["totals"] = G.totals_of(dd)
except Exception as te_:
s["totals_err"] = str(te_)
s["mode"] = _state["mode"] if running() else None
self._send(200, s)
elif self.path == "/api/log":
self._send(200, {"lines": LOG[-400:], "running": running()})
else:
self._send(404, {"ok": False, "msg": "not found"})
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
try:
body = json.loads(self.rfile.read(n).decode("utf-8")) if n else {}
except Exception:
body = {}
if self.path == "/api/dir":
def _normdir(v):
p = (v or "").strip()
if not p:
return ""
p = os.path.normpath(p)
if os.path.isfile(p): # 粘贴了 .db 文件路径 → 取其目录
p = os.path.dirname(p)
return p if os.path.isdir(p) else ""
c0 = _cfg()
t_raw, r_raw = body.get("test_dir"), body.get("ref_dir")
td = _normdir(t_raw) if t_raw is not None else c0.get("data_dir", "")
rd = (_normdir(r_raw) if r_raw else "") if r_raw is not None else c0.get("ref_dir", "")
if not td:
self._send(200, {"ok": False, "msg": "测试库目录无效(目录不存在)"})
elif rd and not (os.path.exists(os.path.join(rd, G.REAL_H))
or os.path.exists(os.path.join(rd, G.TEST_H))):
self._send(200, {"ok": False, "msg": "参考目录里没有 history.db"})
else:
G.set_data_dir(td, rd or None)
self._send(200, {"ok": True, "test_dir": td, "ref_dir": rd})
elif self.path == "/api/run":
cfg = {k: G.DEFAULTS.get(k) for k in G.DEFAULTS}
cfg.update({k: v for k, v in body.items() if k in G.DEFAULTS})
cfg["data_dir"] = G.find_data_dir()
cfg["ref_dir"] = _cfg().get("ref_dir", "")
ok, msg = start_sub("run", cfg)
self._send(200, {"ok": ok, "msg": msg})
elif self.path == "/api/align":
G.REF_DIR = _cfg().get("ref_dir", "") or None
dd = G.find_data_dir()
if not dd:
self._send(200, {"ok": False, "msg": "找不到数据目录"})
else:
try:
n = G.align_testdata(dd, log=log)
self._send(200, {"ok": True, "msg": "已对齐 %d 个批次" % n})
except Exception as e:
self._send(200, {"ok": False, "msg": str(e)})
elif self.path == "/api/switch":
dd = G.find_data_dir()
if not dd:
self._send(200, {"ok": False, "msg": "找不到数据目录"})
else:
try:
G.switch_dbs(dd, log=log)
self._send(200, {"ok": True,
"msg": "换库完成!现在点「启动造价审核.bat」即可查看测试数据。"})
except Exception as e:
self._send(200, {"ok": False, "msg": str(e)})
elif self.path == "/api/delete":
ok, msg = start_sub("delete", {})
self._send(200, {"ok": ok, "msg": msg})
elif self.path == "/api/stop":
self._send(200, {"ok": True, "msg": stop_sub()})
else:
self._send(404, {"ok": False, "msg": "not found"})
PAGE = """<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8">
<title>testdata · 测试数据生成器</title>
<style>
:root{--bg:#f5f6f8;--card:#fff;--line:#e2e5ea;--txt:#1f2329;--sub:#646a73;
--pri:#245bdb;--pri-h:#1c4fc4;--ok:#2ea121;--warn:#d83931;--chip:#eef3ff}
*{box-sizing:border-box;margin:0;padding:0}
body{font:14px/1.6 "Microsoft YaHei",system-ui,sans-serif;background:var(--bg);
color:var(--txt);padding:24px;max-width:1080px;margin:0 auto}
h1{font-size:20px;margin-bottom:4px}
.sub{color:var(--sub);font-size:12px;margin-bottom:16px}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;
padding:16px 20px;margin-bottom:14px}
.card h2{font-size:15px;margin-bottom:12px;padding-left:8px;border-left:3px solid var(--pri)}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px 16px}
.grid .w2{grid-column:span 2}
label{display:block;font-size:12px;color:var(--sub);margin-bottom:2px}
input[type=number],input[type=text],input[type=month],select{
width:100%;padding:5px 8px;border:1px solid var(--line);border-radius:4px;font-size:13px;
background:#fff;color:var(--txt)}
input:focus{outline:none;border-color:var(--pri)}
.pair{display:flex;gap:6px;align-items:center}
.pair input{width:70px}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px}
button{padding:7px 22px;border:none;border-radius:4px;font-size:14px;cursor:pointer;
color:#fff;background:var(--pri)}
button:hover{background:var(--pri-h)}
button.gray{background:#8f959e}button.gray:hover{background:#7a808a}
button.red{background:var(--warn)}button.red:hover{background:#b72e27}
button:disabled{opacity:.45;cursor:not-allowed}
#dd{width:420px}
#log{background:#0d1117;color:#c9d1d9;font:12px/1.55 Consolas,monospace;
height:300px;overflow-y:auto;padding:12px;border-radius:6px;white-space:pre-wrap}
.kpis{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}
.kpi{background:var(--chip);border-radius:6px;padding:6px 12px;font-size:12px}
.kpi b{color:var(--pri);font-size:14px}
.chk{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--txt)}
.sec-h{font-size:12px;color:var(--sub);margin:10px 0 6px;font-weight:bold}
.err{color:var(--warn)}
.banner{display:none;margin:0 0 12px;padding:8px 12px;border-radius:6px;font-size:13px}
.banner.err{background:#fdecea;color:#d83931;border:1px solid #f5c6c0}
.banner.ok{background:#eaf6e8;color:#2ea121;border:1px solid #cde9c8}
.dblab{display:inline-block;width:84px;text-align:center;border-radius:4px;
padding:2px 0;font-size:12px;color:#fff;flex:none}
.dblab.ref{background:#646a73}.dblab.test{background:var(--pri)}
.dbin{flex:1;min-width:260px}
table.assets{border-collapse:collapse;width:100%;font-size:12px}
table.assets th,table.assets td{border:1px solid var(--line,#d5d9e0);
padding:3px 8px;text-align:right}
table.assets th:first-child,table.assets td:first-child{text-align:left}
table.assets th{background:#f2f4f7;font-weight:600}
table.assets .grp td{background:#fafbfc;font-weight:600;text-align:left}
.dbname{font:12px Consolas,monospace}
.badge{font-size:12px;padding:1px 8px;border-radius:10px;flex:none}
.badge.ok{color:var(--ok);background:#eaf6e8}
.badge.no{color:var(--sub);background:#eef0f3}
@media(max-width:860px){.grid{grid-template-columns:repeat(2,1fr)}}
</style></head><body>
<h1>testdata · 测试数据生成器</h1>
<div class="sub">数据目录自动跟随母体(release 包改名/挪动均可)。生成写入<b>独立测试库</b>
history-test.db / session-test.db(首次自动从真实库克隆底子),<b>真实库零污染</b>——
对接软件时把测试库改名换上即可;换到别的母体后点一次「版本对齐」,删除只是兜底手段。</div>
<div id="banner" class="banner"></div>
<div class="card"><h2>数据库</h2>
<div class="row" style="margin-top:0">
<span class="dblab ref">参考数据库</span>
<input type="text" id="refdir" class="dbin" placeholder="留空 = 与测试库同目录">
<button class="gray" onclick="saveDir('ref')">保存</button>
<span id="refok" class="badge"></span><span id="refmsg" class="sub"></span></div>
<div class="row">
<span class="dblab test">测试数据库</span>
<input type="text" id="testdir" class="dbin" placeholder="自动探测……">
<button class="gray" onclick="saveDir('test')">保存</button>
<span id="testok" class="badge"></span><span id="testmsg" class="sub"></span></div>
<div class="sub" style="margin-top:8px">生成只写<b>测试数据库</b>(history-test.db / session-test.db,
附件也落这个目录,对接软件时整个目录拿走换名即可);<b>参考数据库</b>(history.db / session.db)
只读,仅作克隆底子。两框均可直接粘贴目录或 .db 文件路径(自动取其目录)。</div></div>
<div class="card"><h2>一、后台数据(history-test.db)</h2>
<div class="sec-h">入库项目</div>
<div class="grid">
<div><label>项目个数</label><input type="number" id="n_project" value="10" min="0"></div>
<div><label>清单条数/项目(约)</label><div class="pair">
<input type="number" id="bill_lo" value="300"><span>~</span>
<input type="number" id="bill_hi" value="800"></div></div>
<div><label>定额条数/清单</label><div class="pair">
<input type="number" id="norm_lo" value="3"><span>~</span>
<input type="number" id="norm_hi" value="5"></div></div>
<div><label>工料机条数/定额</label><div class="pair">
<input type="number" id="res_lo" value="3"><span>~</span>
<input type="number" id="res_hi" value="5"></div></div>
<div><label>询价附件份数/项目</label><input type="number" id="inq_per_project" value="4" min="0"></div>
<div><label>工料机附件绑定率 %</label><input type="number" id="bind_rate" value="50" min="0" max="100"></div>
</div>
<div class="sec-h">市场价</div>
<div class="grid">
<div><label>份数</label><input type="number" id="n_market" value="20" min="0"></div>
<div><label>每份条数(约)</label><div class="pair">
<input type="number" id="market_lo" value="500"><span>~</span>
<input type="number" id="market_hi" value="800"></div></div>
<div><label>带附件率 %</label><input type="number" id="market_attach_rate" value="80" min="0" max="100"></div>
</div>
<div class="sec-h">信息价</div>
<div class="grid">
<div><label>份数</label><input type="number" id="n_info" value="20" min="0"></div>
<div><label>每份条数(约)</label><div class="pair">
<input type="number" id="info_lo" value="500"><span>~</span>
<input type="number" id="info_hi" value="800"></div></div>
<div><label>带附件率 %</label><input type="number" id="info_attach_rate" value="90" min="0" max="100"></div>
</div></div>
<div class="card"><h2>二、工作台数据(session-test.db)</h2>
<div class="grid">
<div class="w2"><label class="chk"><input type="checkbox" id="session_linked" checked
onchange="linkedChange()"> 与后台项目联动(每份测试项目自动镜像 1 份会话,数量=项目数)</label></div>
<div><label>独立会话份数(不联动时生效)</label><input type="number" id="n_session" value="5" min="0"></div>
<div><label>清单条数/会话(独立时)</label><div class="pair">
<input type="number" id="sbill_lo" value="150"><span>~</span>
<input type="number" id="sbill_hi" value="400"></div></div>
</div></div>
<div class="card"><h2>三、时间跨度</h2>
<div class="grid">
<div><label>期次起(年-月)</label><input type="text" id="from_ym" value="2024-01" placeholder="2024-01"></div>
<div><label>期次止(年-月)</label><input type="text" id="to_ym" value="2026-10" placeholder="2026-10"></div>
</div></div>
<div class="card"><h2>数据库资产总览(全量,含非测试数据)</h2>
<table class="assets" id="assets"></table>
<div class="sub" style="margin-top:6px">打开面板即自动清点;生成前后各看一眼即可对账。
参考库 = history.db / session.db;测试库 = history-test.db / session-test.db。</div></div>
<div class="card"><h2>操作</h2>
<div class="row">
<button id="bRun" onclick="doRun()">开始生成</button>
<button class="gray" onclick="doStop()">停止(软暂停)</button>
<button style="background:var(--ok)" onclick="doSwitch()">一键换库</button>
<button class="red" onclick="doDel()">删除全部测试数据</button>
<button class="gray" onclick="doAlign()">版本对齐</button>
<button class="gray" onclick="loadStats()">刷新统计</button>
</div>
<div class="kpis" id="kpis"></div></div>
<div class="card"><h2>日志</h2><div id="log">就绪。</div></div>
<script>
const IDS=["n_project","bill_lo","bill_hi","norm_lo","norm_hi","res_lo","res_hi",
"inq_per_project","bind_rate","n_market","market_lo","market_hi","market_attach_rate",
"n_info","info_lo","info_hi","info_attach_rate","n_session","sbill_lo","sbill_hi"];
function cfg(){
const c={};IDS.forEach(i=>c[i]=parseInt(document.getElementById(i).value)||0);
c.session_linked=document.getElementById("session_linked").checked;
c.from_ym=document.getElementById("from_ym").value||"2024-01";
c.to_ym=document.getElementById("to_ym").value||"2026-10";
return c;}
function linkedChange(){document.getElementById("n_session").disabled=
document.getElementById("session_linked").checked;}
function banner(msg, cls){
const el=document.getElementById("banner");
if(!el)return;
el.textContent=msg||"";
el.className="banner "+(cls||"ok");
el.style.display=msg?"block":"none";
}
async function req(u,b){
const opt={headers:{"Content-Type":"application/json"}};
if(b!==undefined){opt.method="POST";opt.body=JSON.stringify(b);}else{opt.method="GET";}
const r=await fetch(u,opt);
const txt=await r.text();
let j;try{j=JSON.parse(txt);}catch(e){throw new Error("服务返回异常("+r.status+"):"+txt.slice(0,160));}
return j;
}
async function post(u,b){return req(u,b);}
async function doRun(){try{document.getElementById("bRun").disabled=true;
const r=await post("/api/run",cfg());
banner(r.ok?"已提交生成任务,请观察下方日志。":("开始生成失败:"+(r.msg||"未知错误")),"err");
poll();}catch(e){document.getElementById("bRun").disabled=false;
banner("开始生成失败(服务可能未启动):"+e.message,"err");}}
async function doStop(){try{const r=await post("/api/stop",{});banner(r.msg||"已发送停止信号","");}catch(e){banner("停止失败:"+e.message,"err");}}
async function doDel(){if(!confirm("确认真删除全部「测试」前缀的模拟数据?此操作不可恢复!"))return;
try{await post("/api/delete",{});banner("删除任务已提交,请观察日志。","");poll();}catch(e){banner("删除失败:"+e.message,"err");}}
async function doAlign(){try{const r=await post("/api/align",{});banner(r.msg||"完成","");}catch(e){banner("对齐失败:"+e.message,"err");}}
async function doSwitch(){
if(!confirm("一键换库:测试库换上(history-test.db→history.db),原库留底为 history-y.db / session-y.db。\\n\\n请先关闭造价审核软件,否则文件占用会失败。继续?"))return;
try{const r=await post("/api/switch",{});banner(r.msg||"完成","");loadStats();}catch(e){banner("换库失败:"+e.message,"err");}}
async function saveDir(which){
try{const b={};
if(which==="ref")b.ref_dir=document.getElementById("refdir").value;
else b.test_dir=document.getElementById("testdir").value;
const r=await post("/api/dir",b);
const m=document.getElementById(which+"msg");
if(m)m.textContent=r.ok?"已保存":(r.msg||"失败");
banner(r.ok?"路径已保存":("保存失败:"+(r.msg||"未知错误")), r.ok?"":"err");
loadStats();}catch(e){banner("保存失败(服务可能未启动):"+e.message,"err");}}
function kpi(t,v,cls){return '<div class="kpi">'+t+' <b'+(cls?' class="'+cls+'"':'')+'>'+v+'</b></div>';}
async function loadStats(){
try{const s=await req("/api/stats");
const rf=document.getElementById("refdir"),tf=document.getElementById("testdir");
if(document.activeElement!==rf)rf.value=s.ref_dir||"";
if(document.activeElement!==tf)tf.value=s.test_dir||s.data_dir||"";
const ro=(s.ref_ok||[]).length?s.ref_ok.every(x=>x):false;
const re=document.getElementById("refok");
re.textContent=ro?"在":"缺";re.className="badge "+(ro?"ok":"no");
const to=(s.test_ok||[]).length?s.test_ok.every(x=>x):false;
const te=document.getElementById("testok");
te.textContent=to?"已生成":"尚未生成";te.className="badge "+(to?"ok":"no");
let h="";
h+=kpi("后台项目",s.b_project??0);h+=kpi("市场价",s.b_market??0);h+=kpi("信息价",s.b_info??0);
h+=kpi("清单",s.bills??0);h+=kpi("定额",s.norms??0);h+=kpi("定额消耗",s.norm_res??0);
h+=kpi("工料机",s.lmes??0);h+=kpi("价格明细",s.prices??0);
h+=kpi("询价附件",s.inquiry_files??0);h+=kpi("绑定",s.lme_attach??0);
h+=kpi("价格原件批次",s.price_attach_batches??0);
h+=kpi("工作台会话",s.s_sessions??0);
document.getElementById("kpis").innerHTML=h;
renderAssets(s.totals);
if(s.totals_err)banner("资产清点失败:"+s.totals_err,"err");
}catch(e){banner("无法连接服务,请确认「启动testdata.bat」已运行、且 8412 端口未被旧实例占用:"+e.message,"err");}}
function renderAssets(t){
const el=document.getElementById("assets");
if(!t){el.innerHTML='<tr><td>暂无数据(数据目录未就绪)</td></tr>';return;}
const occ=new Set(t.locked||[]);
const occH=occ.has("参考history"),occTH=occ.has("测试history");
const occS=occ.has("参考session"),occTS=occ.has("测试session");
const fmt=(v,occupied)=>occupied?"占用":(v==null?"缺文件":(v<0?"-":v.toLocaleString()));
const HH=[["batches","批次"],["bills","清单"],["norms","定额"],["norm_res","定额消耗"],
["lmes","工料机"],["lme_lib","价格库"],["prices","价格明细"],["attachments","附件"]];
const SS=[["sessions","会话"],["s_bills","清单"],["s_norms","定额"],["s_lmes","工料机"]];
let h='<tr><th>指标</th><th>参考库 history</th><th>测试库 history-test</th><th>参考库 session</th><th>测试库 session-test</th></tr>';
HH.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>'+fmt((t.ref_h||{})[k],occH)
+'</td><td>'+fmt((t.test_h||{})[k],occTH)+'</td><td>—</td><td>—</td></tr>';});
SS.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>—</td><td>—</td><td>'+fmt((t.ref_s||{})[k],occS)
+'</td><td>'+fmt((t.test_s||{})[k],occTS)+'</td></tr>';});
if(occ.size)h+='<tr><td colspan="5" style="color:#d83931;text-align:left">⚠ 以下库被占用(造价审核软件打开中或正在生成),数字暂不可用,稍后点「刷新统计」:'+[...occ].join("、")+'</td></tr>';
el.innerHTML=h;}
let last=0;
async function poll(){try{const r=await req("/api/log");
if(r.lines.length!==last){const el=document.getElementById("log");
el.textContent=r.lines.join("\\n");el.scrollTop=el.scrollHeight;last=r.lines.length;}
loadStats();
const run=r.running;
document.getElementById("bRun").disabled=run;
if(run)setTimeout(poll,1200);}catch(e){banner("日志读取失败:"+e.message,"err");}}
linkedChange();loadStats();poll();
</script></body></html>"""
def _kill_port(port):
"""Windows:结束占用本端口的进程(多半是上次没退干净的旧面板),
保证本次启动的是当前代码。netstat 在中文 Windows 输出为 GBK,必须按 gbk 解码,
否则 utf-8 解码抛 UnicodeDecodeError 会被静默吞掉、导致清场失效。"""
try:
out = subprocess.run(["netstat", "-ano"], capture_output=True,
encoding="gbk", errors="ignore", timeout=5).stdout
for line in out.splitlines():
if (":%d" % port in line) and "LISTENING" in line:
pid = line.split()[-1]
try:
subprocess.run(["taskkill", "/f", "/pid", pid],
capture_output=True, timeout=5)
except Exception:
pass
except Exception:
pass
def main():
# 启动前先清掉占用 8412 的旧面板。Windows 上 SO_REUSEADDR 允许多个进程同时
# bind 同一端口(bind 不报错),旧实例会继续应答、导致新代码不生效,因此必须主动清场。
log("启动前清理 8412 端口上的旧实例…")
_kill_port(PORT)
time.sleep(1)
try:
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
except OSError:
log("端口 %d 仍被占用(可能无权限结束旧进程),直接打开浏览器指向现有面板。" % PORT)
webbrowser.open("http://127.0.0.1:%d" % PORT)
return
log("testdata 控制台:http://127.0.0.1:%d" % PORT)
threading.Timer(0.6, lambda: webbrowser.open("http://127.0.0.1:%d" % PORT)).start()
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()