nested embedding of interpreter

Eric Frederich eric.frederich at
Mon Feb 6 09:39:21 EST 2012


I work with a 3rd party tool that provides a C API for customization.

I created Python bindings for this C API so my customizations are nothing
more than this example wrapper code almost verbatim:
I have many .c files just like that only differing by the module and
function that they load and execute.

This has been working fine for a long time.  Now, as we add more and more
customizations that get triggered at various events we have come to a
If some of the Python customization code gets triggered from inside another
Python customization I get a segfault.
I thought this might have something to do with the nesting which is the
equivalent of calling Py_Initialize() twice followed by Py_Finalize() twice.
I went into the C wrapper code for the inner-most customization and
commented out the Py_Initialize and Py_Finalize calls and it worked nicely.
Further testing showed that I only needed to remove the Py_Finalize call
and that calling Py_Initialize twice didn't cause a segfault.

So, now that I think I verified that this is what was causing the segfault,
I'd like to ask some questions.

Is calling Py_Initialize twice correct, or will I run into other problems
down the road?

Another option I have is that I can remove all Py_Initialize / Py_Finalize
calls from the individual customizations and just call Py_Initialize once
when a user first starts the program.  I am not sure if there is a
mechanism to get something called at the end of the user's session with the
program though, so is it a problem if I don't call Py_Finalize at the end?

Is there a proper way to nest these things?  I imagine not since
Py_Finalize doesn't take any arguments.  If I could do...
    int session = Py_Initialize()
But obviously, CPython is not coded that way so it is not supported.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list