[Python] How to retrive PyObject_Call exception as C string?

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to debug why a call to a Python object isn't working on one environment. Unfortunately, I can't figure out how to get the error back somewhere I can see it.

    I tried PyErr_PrintEx(), but it just vanishes into the void. So, I'm trying to retrieve it more manually.

    Here's what I have so far:

    PyObject* mod = PyImport_ImportModule("myModule");
    PyObject* dict = PyModule_GetDict(mod);
    // (Some args are initialized before this point, please ignore)
    PyObject* mainWindow = PyDict_GetItemString(dict, "MainWindow");
    PyObject* myObject = PyObject_Call(mainWindow, args, NULL);

    if (!myObject )
    {
    if (PyErr_Occurred())
    {
    // Try to get the error as a C string
    PyObject *type, *value, *traceback;
    PyErr_Fetch(&type, &value, &traceback);
    PyErr_NormalizeException(&type, &value, &traceback);
    // This should turn 'value' into a python exception object?
    PyObject *errStr = PyObject_Str(value);
    char *pStrErrorMessage = PyUnicode_AsUTF8(errStr);
    std::string errString(pStrErrorMessage);
    }
    }


    This does return a string, but it's a single word and I'd assume something went wrong with formatting/concatonating it all together and the rest is missing.

    How do I properly get the python exception inside C/C++? (Boost unavailable)

    Continue reading...

Compartilhe esta Página