c中獲取python的異常的traceback

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);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章