Python Segmentation fault 错误定位办法

📅 2026/7/10 13:04:28
Python Segmentation fault 错误定位办法
1. 说明Python 3 执行某一个程序时报 Segmentation fault (core dumped) 错但没有告知到底哪里出错无法查问题这时就需要一个库faulthandler来帮助分析。2. 安装faulthandlerfaulthandler 在 Python 3.3 之后成为标准库对于以前的版本运行如下命令pip install pytest-faulthandler3. Python 3 使用 faulthandler3.1. 使用方式可以通过 import 到代码中启用也可以直接通过命令行来启用。通过 import 到代码中来启用import faulthandler # 在import之后直接添加以下启用代码即可 faulthandler.enable() # 后边正常写你的代码直接通过命令行来启用运行时添加-X faulthandler参数即可python3 -X faulthandler my_script.py3.2. 使用效果演示代码示例建议在Linux上运行该代码import traceback def test_segmentation_fault(): # 对于segmentation fault并不能catch到异常即此处try没效果 try: ctypes.string_at(0) except Exception as e: print(traceback.format_exc()) if __name__ __main__: test_segmentation_fault()如下图所示在未使用faulthandler时try不生效完全不知道哪里出了问题在使用faulthandler后能打印出导致退出的地方4. Python 2 使用 faulthandlerfaulthandler 在 Python 2 中不是标准库需要另行安装。另外随着 faulthandler 在 Python 3 中成为标准库及 Python 2 不再维护作者也不再更新 faulthandlerpip install faulthandler由于Python 2也不支持-X参数所以faulthandler在Python 2中只能通过import到代码中来启用import faulthandler # 在import之后直接添加以下启用代码即可 faulthandler.enable() # 后边正常写你的代码参考文献Python Segmentation fault错误定位办法 - 诸子流 - 博客园python遇到Segmentation fault (core dumped)调试方法 - DoubleLi - 博客园faulthandler —— 转储 Python 的跟踪信息 — Python 3.10.2 文档