I was looking for a way to get error message from executing python code in C++. I tried some answers from How to get Python exception text, but any of them worked for me. Can someone explain me what I'm doing wrong?
#include <iostream>
#include <Python.h>
int main() {
Py_Initialize();
if (PyRun_SimpleString("something stupid")) {
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
const char *errMsg = PyUnicode_AsUTF8(PyObject_Str(ptraceback));
std::cout << errMsg;
}
Py_Finalize();
}
I expect to print something like that:
File "<string>", line 1
something stupid
^
SyntaxError: invalid syntax
But when I run code, cout
prints:
<NULL>