nested embedding of interpreter

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


Hello,

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:
    http://docs.python.org/extending/embedding.html#pure-embedding
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
problem.
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.

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

2)
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?

3)
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()
    Py_Finalize(session)
But obviously, CPython is not coded that way so it is not supported.

Thanks,
~Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120206/cdf5f43e/attachment.html>


More information about the Python-list mailing list