1. 说明

Python 3 执行某一个程序时,报 Segmentation fault (core dumped) 错,但没有告知到底哪里出错,无法查问题,这时就需要一个库faulthandler来帮助分析。

2. 安装faulthandler

faulthandler 在 Python 3.3 之后成为标准库,对于以前的版本运行如下命令

pip install pytest-faulthandler

3. Python 3 使用 faulthandler

3.1. 使用方式

可以通过 import 到代码中启用,也可以直接通过命令行来启用。

通过 import 到代码中来启用:

import faulthandler
# 在import之后直接添加以下启用代码即可

faulthandler.enable()
# 后边正常写你的代码

直接通过命令行来启用,运行时添加-X faulthandler参数即可:

python3 -X faulthandler my_script.py

3.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 使用 faulthandler

faulthandler 在 Python 2 中不是标准库,需要另行安装。(另外随着 faulthandler 在 Python 3 中成为标准库及 Python 2 不再维护,作者也不再更新 faulthandler)

pip 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 文档

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐