当用户拒绝上传 dump 时,如何本地提示并生成可读栈追踪?
解读
国内 Pygame 作品上线前常做“灰度内测”,测试者普遍担心隐私泄露而拒绝上传崩溃 dump。面试官想知道:
- 你能否在不依赖外部服务的前提下,把异常现场留下来;
- 留下的信息必须足够定位到 Python 层甚至 C 扩展层;
- 提示方案要符合国产系统权限习惯(Windows 弹窗、macOS 通知、Linux 桌面气泡),且不能阻塞游戏主循环。
一句话:把“上传”改为“本地保存+友好提示”,同时保证栈追踪可读、可检索、可后续手动回传。
知识点
- Python 标准库:traceback、faulthandler、sys.excepthook,分别捕获 Python 异常、C 段错误、全局未处理异常。
- Pygame 事件循环:异常不能直接把主线程炸掉,需在事件循环外层包 try/except,并把异常投递到自定义事件,保证帧率不崩。
- 本地 I/O:用 pathlib 写到
%APPDATA%/YourGame/crash/(Win)、~/Library/Application Support/YourGame/crash/(macOS)、~/.local/share/YourGame/crash/(Linux),文件名带时间戳与版本号,避免覆盖。 - 用户提示:
- Windows:ctypes 调 MessageBoxW,不依赖 tkinter,减少包体积;
- macOS:os.system 调 osascript 发通知;
- Linux:dbus-send 或 notify-send,失败则静默写日志。
- 可读性增强:
- 栈追踪里混有 C 扩展帧时,自动调用 faulthandler.dump_traceback_later(0) 把 native 栈追加到同一文件;
- 用 pygments 高亮代码片段,写入同名 .html,方便测试者直接双击查看;
- 把 sys.modules 快照、pygame.version.ver、Python 版本、OpenGL 渲染器、当前分辨率一并写入 crash_meta.json,方便后端复现。
- 合规:文件体积控制在 2 MB 以内,不写注册表、不碰敏感目录,通过国内隐私审核。
答案
# crash_handler.py
import os, sys, json, traceback, pathlib, time, platform
import pygame
import faulthandler
from datetime import datetime
from ctypes import windll, c_int, c_wchar_p
VERSION = "1.0.0"
CRASH_DIR = {
"Windows": pathlib.Path(os.getenv("APPDATA")) / "YourGame" / "crash",
"Darwin": pathlib.Path.home() / "Library" / "Application Support" / "YourGame" / "crash",
"Linux": pathlib.Path.home() / ".local" / "share" / "YourGame" / "crash",
}[platform.system()]
CRASH_DIR.mkdir(parents=True, exist_ok=True)
def _local_msg_box(path: pathlib.Path):
"""不依赖 tkinter 的极简弹窗"""
if platform.system() == "Windows":
windll.user32.MessageBoxW(
0,
c_wchar_p(f"游戏崩溃,诊断报告已保存至:\n{path}\n请将文件发送给开发者,谢谢!"),
c_wchar_p("抱歉出错了"),
c_int(0x30),
)
def make_report(exc_type, exc_value, exc_tb) -> pathlib.Path:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
txt_path = CRASH_DIR / f"crash_{VERSION}_{ts}.txt"
html_path = txt_path.with_suffix(".html")
# 1. Python 栈
with open(txt_path, "w", encoding="utf-8") as f:
f.write(f"Version: {VERSION}\n")
f.write(f"Python: {sys.version}\n")
f.write(f"Pygame: {pygame.version.ver}\n")
f.write("----- Python traceback -----\n")
traceback.print_exception(exc_type, exc_value, exc_tb, file=f)
# 2. Native 栈
faulthandler.dump_traceback(open(txt_path, "a", encoding="utf-8"), all_threads=True)
# 3. 元数据
meta = {
"time": ts,
"platform": platform.platform(),
"resolution": pygame.display.get_window_size() if pygame.display.get_init() else None,
"modules": len(sys.modules),
}
with open(txt_path.with_suffix(".json"), "w", encoding="utf-8") as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
# 4. 可选高亮 HTML
try:
from pygments import highlight
from pygments.lexers import PythonTracebackLexer
from pygments.formatters import HtmlFormatter
with open(html_path, "w", encoding="utf-8") as f:
f.write(highlight(txt_path.read_text(), PythonTracebackLexer(), HtmlFormatter(full=True)))
except ImportError:
pass
return txt_path
def install_handler():
def hook(exc_type, exc_value, exc_tb):
path = make_report(exc_type, exc_value, exc_tb)
_local_msg_box(path)
# 不退出,直接恢复,避免 GameJam 演示尴尬
pygame.event.post(pygame.event.Event(pygame.USEREVENT, {"action": "recover"}))
sys.excepthook = hook
# 主程序入口
def main():
pygame.init()
install_handler()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.USEREVENT and event.dict.get("action") == "recover":
# 这里可以做场景重启、资源重载
print("捕获异常,已恢复事件循环")
screen.fill((30, 30, 30))
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main()
运行效果:
- 任何未捕获异常都会生成三件套:.txt(完整栈)、.json(环境)、.html(高亮);
- 弹出系统级中文提示框,用户点击“确定”后游戏继续运行;
- 全程零网络、零上传,符合国内隐私合规要求;
- 文件体积 < 1 MB,方便测试者微信/QQ 手动回传。
拓展思考
- 如果游戏使用 PyInstaller 打包,需在 spec 文件中
--hidden-import pygments.lexers.python_traceback保证高亮模块被打入,否则回退到纯文本。 - 对于段错误(如 OpenGL 驱动崩溃),Python 层 except 无法捕获,可在启动子进程时加
faulthandler.enable(file=open(CRASH_DIR/'segfault.txt','w'), all_threads=True),把致命信号也落到同一目录。 - 国内安卓 Pygame 分支(pydroid3、pygame-sdl2)没有桌面通知,可改用 pygame.freetype 渲染提示文字到 Surface,强制弹一个“全屏半透明崩溃遮罩”,用户点击后自动打开文件管理器(
os.startfile或xdg-open)。 - 若团队使用 Sentry 企业版内网镜像,可再做一个“自愿上传”按钮:读取本地 crash 文件,二次加密(AES-128-CFB)后通过 HTTPS 内网域名上传,密钥每日轮换,满足国企安全审计。
- 教学场景:把 crash 文件自动复制到 U 盘根目录,学生交作业时一并提交,老师用 VS Code 插件“Python Traceback Highlighter”一键可视化,减少助教工作量。