Python技巧之使用“faulthandler”标准库模块

Python 3.3有一个标准库模块,用于展示回溯,即使Python“dies”。例如,下面为一个段错误在启用错误操作器前后的标准输出:

$ python3 -c "import ctypes; ctypes.string_at(0)"
Segmentation fault

$ python3 -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700 (most recent call first):
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault

使用错误操作器的方法有两种:

  1. 调用faulthandler.enable()
  2. 使用命令行选项-X faulthandler,用于设置环境变量PYTHONFAULTHANDLER

默认回溯信息输出到标准输出,你可以设置转储文件:

#方法一
faulthandler.dump_traceback(file=sys.stderr, all_threads=True)
#方法二
faulthandler.enable(file=sys.stderr, all_threads=True)

评论

暂无评论