I have a C++/Qt application where I am running a Python interpreter session within the process of the main application. I have built a ‘python console’ as a QPlainTextEdit widget, which handles the input and output for the interpreter using the Python C API. The point of all this is that Python will have direct access to data that I’m holding inside the main application. All is well, except that I want to be able to end the current interpreter session and restart it without exiting the main application.
Currently, I’m trying the obvious way:
Py_Initialize();
// Run the main session...
Py_FinalizeEx();
// Restart the session
Py_Initialize();
From reading other posts and Python’s documentation, there are possibly issues with reloading certain modules after finalizing the interpreter due to memory leaks. This seems to be true in my case: re-importing certain modules (like ‘numpy’) but not others (like ‘sys’) will trigger an exception and fail.
Is there a good workaround strategy to restart the interpreter without these issues? For instance, if I spawn a sub-interpreter, will finalizing it and restarting a new sub-interpreter run into the same problems I’m having? The alternative I was trying to avoid is to run Python out-of-process, which I think would allow me to restart by basically killing the process and starting a new one. Any strategy advice would be much appreciated.
Ben Murphy-Baum is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.