c中获取python的异常的traceback

来源:互联网 发布:蒙特卡洛算法求圆周率 编辑:程序博客网 时间:2024/05/20 07:58

1、如果是一般的控制台程序,可以使用PyErr_Print();错误信息会直接打印到控制台上
2、如果不是控制台程序,则需要使用PyErr_Fetch(PyObject**,PyObject**,PyObject**,PyObject**)
下面是代码实例:(来自Stack Overflow)

char* full_backtrace; // 保存traceback
PyObject* ptype,*pvalue,*ptraceback;
PyObject* pystr,*module_name,*pyth_module,*pyth_func;
char *str;
PyErr_Fetch(&ptype,&pvalue,&ptraceback);
pystr = PyObject_Str(pvalue);
str= PyString_AsString(pystr);
char* error_description = strdup(str);
module_name = PyString_FromString(“traceback”);
pyth_module = PyImport_Import(module_name);
Py_DECREF(module_name);
if (pyth_module == NULL) {
full_backtrace = NULL;
return;
}
pyth_func = PyObject_GetAttrString(pyth_module, “format_exception”);
if (pyth_func && PyCallable_Check(pyth_func)) {
PyObject *pyth_val;
pyth_val = PyObject_CallFunctionObjArgs(pyth_func, ptype, pvalue, ptraceback, NULL);
pystr = PyObject_Str(pyth_val);
str = PyString_AsString(pystr);
full_backtrace = strdup(str);
Py_DECREF(pyth_val);
}

0 0
原创粉丝点击