3

This is a known problem, but I want to ask the experts for the best way to solve it for me.

I have a project (Euler Math Toolbox), which runs Python as a script language. For this, a library module "python.dll" is loaded at run time, which is linked against "python27.lib". Then Py_Initialize is called. This all works well.

But Euler can be restarted by the user with a new session and notebook. Then I want Python to clear all variables and imports. For this, I call Py_Finalize and unload "python.dll". When Python is needed, loading and initializing starts Python again.

This works. But Python crashes at the first call, if MatPlotlib is imported in the previous session. It seems that Py_Finalize does not completely clear Python, nor does unloading my "python.dll". I tried unloading "python27.dll" (the Python DLL), but this does not help. Most likey, another DLL remains active, but corrupts during Py_Finalize.

To solve this, it would suffice to clear all variables and imports. I could live with not calling Py_Finalize. But how?

PS: You may wonder, why I do not directly link euler.exe to Python. The reason is that this prevents Euler form starting, if Python is not installed, even if it is never needed.

Thanks for any answers! You duplicate your answer to renegrothmann at gmail, if you like. That would help me.

1 Answer 1

2

To solve this, it would suffice to clear all variables and imports. I could live with not calling Py_Finalize. But how?

Provided you properly release all references after each call, this should work fine. Just make sure to only call Py_Initialize a single time, and never call Py_Finalize. Run each "session" using a separate dictionary, and always decrement the reference counts properly when you're done with them (which will release those variables after running your code).

On a side note - this is a common issue. Many other packages, such as numpy, or any package written using Boost::Python will exhibit the same behavior if you use Py_Finalize.

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

2 Comments

How do I run with a "separate dictionary"? I am loading the main module with "pModule = PyImport_AddModule("main");". Then I use this module e.g. for PyRun_SimpleString(string).
@Rene You can't use PyRun_SimpleString - you'll need to use something like PyEval_EvalCode or one of the alternatives that lets you specify the dictionary in which the code executes.

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.