Python Forum

Full Version: Pipe traceback to a C program
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to embed Python in a C program. It works fine if I simply want to execute something simple. Here's the C code:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

/*
compile with 
gcc -I/usr/include/python3.11 -o embed_python embed_python.c -L/usr/lib -lpython3.11
*/

int
main(int argc, char *argv[])
{
	int err;
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    //Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
	err = PyRun_SimpleString("print(\"hello!\")");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}
In the docs I've read that there is no way to get the error information with this high level embedding. If the Python line I try to execute is wrong, I do get the traceback printed onto my console. Is there absolutely no way to pipe this information to the C program? I guess not, but I'm just hoping.