Python 3.3有一个标准库模块,用于展示回溯,即使Python“dies”。例如,下面为一个段错误在启用错误操作器前后的标准输出:
1$ python3 -c "import ctypes; ctypes.string_at(0)" 2Segmentation fault 3 4$ python3 -q -X faulthandler 5>>> import ctypes 6>>> ctypes.string_at(0) 7Fatal Python error: Segmentation fault 8 9Current thread 0x00007fb899f39700 (most recent call first): 10 File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at 11 File "<stdin>", line 1 in <module> 12Segmentation fault
使用错误操作器的方法有两种:
- 调用
faulthandler.enable() - 使用命令行选项
-Xfaulthandler,用于设置环境变量PYTHONFAULTHANDLER
默认回溯信息输出到标准输出,你可以设置转储文件:
1#方法一 2faulthandler.dump_traceback(file=sys.stderr, all_threads=True) 3#方法二 4faulthandler.enable(file=sys.stderr, all_threads=True)