std::string getPythonErrorInfo(void) {
string errorMsg = "";
PyObject *pType, *pValue, *pTraceback;
PyErr_Fetch(&pType, &pValue, &pTraceback);
if (pValue == nullptr) {
return errorMsg;
}
if (pTraceback == nullptr) {
errorMsg += PyUnicode_AsUTF8(pValue);
} else {
PyErr_NormalizeException(&pType, &pValue, &pTraceback);
PyObject *pTraceModule = PyImport_ImportModule("traceback");
if (pTraceModule != nullptr) {
PyObject *pModuleDict = PyModule_GetDict(pTraceModule);
if (pModuleDict != nullptr) {
PyObject *pFunc = PyDict_GetItemString(pModuleDict, "format_exception");
if (pFunc != nullptr) {
PyObject *errList = PyObject_CallFunctionObjArgs(pFunc, pType, pValue,
pTraceback, nullptr, nullptr);
if (errList != nullptr) {
int listSize = PyList_Size(errList);
for (int i = 0; i < listSize; ++i) {
auto item = PyList_GetItem(errList, i);
errorMsg += PyUnicode_AsUTF8(item);
}
Py_XDECREF(errList);
}
Py_XDECREF(pFunc);
}
Py_XDECREF(pModuleDict);
}
Py_XDECREF(pTraceModule);
}
}
Py_XDECREF(pType);
Py_XDECREF(pValue);
Py_XDECREF(pTraceback);
return errorMsg;
}