While working with the Python C API, I found that the python interpreter crashes when initializing it a second time and executing import numpy
after each initilization. Any other command (e.g. import time
) will do just fine.
#include <Python.h>
int main(int argc, char ** argv)
{
while(1){
printf("Initializing python interpreter...\n");
Py_Initialize();
if(PyRun_SimpleString("import numpy")) {
exit(1);
}
printf("Finalizing python interpreter...\n");
Py_Finalize();
}
return 0;
}
The above program crashes on both of my test systems (ubuntu and manjaro, no matter what python version I use) with a Segmentation Fault while executing import numpy
a second time.
The Documentation (https://docs.python.org/3/c-api/init.html?#c.Py_FinalizeEx) indeed says that: Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.
But shouldn't there be a way to properly clear the memory of the interpreter so it can be initialized multiple times? For example if I have a program that allows the user to run a custom python script, it should be possible to run the same script multiple times without restarting the program. Any clues?