Skip to content

Crash when importing numpy from the Python C-API after calling Py_Finilize() #8097

@phelippeneveu

Description

@phelippeneveu

Hi,

We are getting a crash in the numpy code when importing numpy after Py_Finalize() is called. If we comment out the call to Py_Finalize() the second import will be successful.

#include "python2.7/Python.h"

int RunPythonScript(const char * pszScript)
{
    Py_Initialize();

    int nResult = PyRun_SimpleStringFlags(pszScript, NULL);

    Py_Finalize();

    return nResult;
}

int main(void)
{
    RunPythonScript("import numpy");

    printf("First import of numpy ran successfully!\n");

    RunPythonScript("import numpy");

    printf("Second import of numpy ran successfully!\n");

    return 0;
}

I compiled this example using GCC: gcc -o numpy_crash numpy_crash.cpp -lpython2.7

This simple example should not crash. My guess is that Python will destroy some global objects when Py_Finalize() is called. But these global objects are still referenced in the numpy code. You would need to register an atexit function using Py_AtExit() to reinitialize any global objects to NULL so that they are re-created on subsequent import of numpy.

This bug is most likely the same bug as #656 and #3961. But we are only running a single Python interpreter. We call Py_Finalize() every time a user runs a new Python script so that the variables they defined on the previous runs are no longer available in the Python environment.

Regards,

Phelippe Neveu

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions