-1

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>
IzZy
  • 364
  • 3
  • 16
  • There's a lot of error checking that you're missing tht you might help. Check if `ptraceback` is NULL. Check if the result of `PyObject_Str(ptraceback)` is NULL. – DavidW Jul 23 '21 at 07:42
  • I checked and both are NULL – IzZy Jul 23 '21 at 09:11

1 Answers1

0

According to documentation (https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleStringFlags), when using PyRun_SimpleStringFlags() (or just PyRun_SimpleString()):

If there was an error, there is no way to get the exception information.

So code must be runned the other way. Eventually, you can run in interpreter:

PyRun_SimpleString("import traceback, sys");
PyRun_SimpleString("trace = ''.join(traceback.format_exception(sys.last_type, sys.last_value, sys.last_traceback))");

Then read trace from interpreter, similar like in this answer https://stackoverflow.com/a/63320285/13966135 .

IzZy
  • 364
  • 3
  • 16