-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>
2
  • 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. Commented Jul 23, 2021 at 7:42
  • I checked and both are NULL Commented Jul 23, 2021 at 9:11

1 Answer 1

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 .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.