feat: 添加工具以查找重复的异常处理,增强代码质量检查;新增验证 GUI 回退方式的自检脚本

This commit is contained in:
Your Name committed 2026-01-05 21:32:50 +08:00
1 parent 982357927e
commit 43e39f4db6
16 files changed
+472 -180

No files matched your search

+6 -4
View File
@@ -14,7 +14,7 @@ _project_root = os.path.dirname(_script_dir)
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
from PIL import Image, ImageTk
from PIL import Image, ImageTk # type: ignore[import]
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
from gui.gui_core import (
@@ -2810,7 +2810,9 @@ def main():
(".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif")
):
# 获取相对路径
rel_path = os.path.relpath(os.path.join(root, file), images_dir)
rel_path = os.path.relpath(
os.path.join(root, file), str(images_dir)
)
# 统一使用正斜杠(Windows和Unix都支持)
rel_path = rel_path.replace("\\", "/")
image_files.append(rel_path)
@@ -3164,7 +3166,7 @@ def main():
seconds = uptime_seconds % 60
lines.append(f"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}")
else:
lines.append(f"运行时长: -")
lines.append("运行时长: -")
last_log_ts = stats.get("last_log_ts")
if last_log_ts:
@@ -4099,7 +4101,7 @@ def main():
lines.append(
f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}"
)
lines.append(f"│")
lines.append("│")
lines.append(f"│ 📝 记录时间:{created_str_full}")
lines.append(f"└{'─' * 58}")
lines.append("")
+5 -2
View File
@@ -50,6 +50,7 @@ def list_adb_devices(adb_exe: str) -> list[str]:
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
except FileNotFoundError:
return []
@@ -1020,13 +1021,13 @@ class Runner:
f"Python路径: {sys.executable}\n"
f"run_cli.py路径: {run_cli_path}\n"
f"原始错误: {e}"
)
) from e
except Exception as e:
raise RuntimeError(
f"启动进程失败:{e}\n"
f"命令: {' '.join(cmd)}\n"
f"工作目录: {path_config.PROJECT_ROOT}"
)
) from e
with self._lock:
self._proc = p
@@ -1127,6 +1128,7 @@ class Runner:
encoding="utf-8",
errors="replace",
timeout=5.0,
check=False,
)
if proc.returncode == 0:
@@ -1182,6 +1184,7 @@ class Runner:
["taskkill", "/PID", str(pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
else:
# 类 Unix:尝试向进程组发送 SIGKILL
+14 -15
View File
@@ -57,6 +57,7 @@ def list_adb_devices(adb_exe: str) -> list[str]:
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
except FileNotFoundError:
return []
@@ -118,6 +119,12 @@ class ProcRunner:
"updated_ts": None,
}
# 延迟属性:预先声明,避免静态检查报“在 __init__ 外定义属性”
self._log_permission_warned: bool = False
self._log_write_error_warned: bool = False
self._current_trace_id: str = ""
self._mdc_context: dict[str, str] = {}
# 事件流(用于趋势/分布/Top 统计),保留最近 N 条
self._events: list[dict] = []
self._events_cap: int = 5000
@@ -166,13 +173,13 @@ class ProcRunner:
f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失
except PermissionError as e:
# 权限错误,只输出一次警告避免刷屏
if not hasattr(self, "_log_permission_warned"):
if not self._log_permission_warned:
print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_permission_warned = True
except Exception as e:
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
if not hasattr(self, "_log_write_error_warned"):
if not self._log_write_error_warned:
print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_write_error_warned = True
@@ -277,7 +284,7 @@ class ProcRunner:
if trace_id_match:
trace_id = trace_id_match.group(1)
# 存储当前traceId(用于统计和显示)
if not hasattr(self, "_current_trace_id"):
if not self._current_trace_id:
self._current_trace_id = trace_id
elif trace_id != "N/A":
self._current_trace_id = trace_id
@@ -290,8 +297,6 @@ class ProcRunner:
mdc_pairs = re.findall(r"(\w+)=([^,\s]+)", mdc_str)
for key, value in mdc_pairs:
# 存储MDC信息(可用于统计)
if not hasattr(self, "_mdc_context"):
self._mdc_context = {}
self._mdc_context[key] = value
# --- 福袋:抽取"最近一次"识别到的信息 ---
@@ -1424,7 +1429,7 @@ class ProcRunner:
self._append_log(f"[网页] 读取线程启动,监视 PID={p.pid}")
out = p.stdout
if out is None:
self._append_log(f"[网页] 读取线程:stdout 为 None,无法读取子进程输出")
self._append_log("[网页] 读取线程:stdout 为 None,无法读取子进程输出")
try:
rc = p.wait()
except Exception:
@@ -1448,7 +1453,7 @@ class ProcRunner:
pass
except BrokenPipeError:
# 进程已关闭stdout
self._append_log(f"[网页] 读取线程:子进程stdout已关闭")
self._append_log("[网页] 读取线程:子进程stdout已关闭")
except Exception as e:
self._append_log(f"[网页] 读取线程异常:{e}")
@@ -1456,7 +1461,7 @@ class ProcRunner:
rc = p.wait(timeout=1)
except subprocess.TimeoutExpired:
rc = None
self._append_log(f"[网页] 等待进程退出超时,强制终止")
self._append_log("[网页] 等待进程退出超时,强制终止")
try:
p.kill()
rc = p.wait(timeout=5)
@@ -1691,7 +1696,7 @@ class Handler(BaseHTTPRequestHandler):
if not safe.startswith("pic/"):
self.send_error(HTTPStatus.FORBIDDEN)
return
full = os.path.join(path_config.PROJECT_ROOT, safe)
full = os.path.join(str(path_config.PROJECT_ROOT), safe)
if not os.path.isfile(full):
self.send_error(HTTPStatus.NOT_FOUND)
return
@@ -1893,12 +1898,6 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(HTTPStatus.NOT_FOUND)
def log_message(self, format, *args): # type: ignore[override]
# 覆盖基类方法以抑制日志输出
# 参数名从 fmt 改为 format 以匹配基类签名
return
def main() -> int:
host = "127.0.0.1"
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000