Embedding numpy works once, but not twice??

Deepak Chandran dchandran1 at tinkercell.com
Sun Feb 1 06:47:27 CET 2009


I have a program in which I have successfully embedded Python. Now, I want
to include NumPy as well (and other modules). I am able to import numpy
once. Then I close the python console in my program and then re-open it.
When I try to import numpy for a second time, the program crashes. Below is
a simple version of the problem.

The main() import numpy twice. The first import works fine -- prints "no
errors.". But the second load crashes the program. What is going on here?

By the way, this is all in Windows (XP and Vista have same problem) using
python25.dll (since numpy does not work for python26.dll). I am using MinGW
compiler.

#include <stdlib.h>
#include <stdio.h>
#include <Python.h>

int load(char * code)
{
PyObject *errobj, *errdata, *errtraceback, *pystring;
int retval;

       Py_Initialize();

PyObject *main = PyImport_AddModule("__main__");
PyObject* main_dict = PyModule_GetDict( main );

PyObject * rstring = PyRun_String( code, Py_file_input, main_dict, main_dict
); //the second main_dict was my_program_dict originally
 PyErr_Fetch (&errobj, &errdata, &errtraceback);
 if (errdata != NULL)
{
PyObject *s = PyObject_Str(errdata);
char * c = PyString_AS_STRING(s);
printf("%s\n",c);                   //print any errors
Py_DECREF(s);
}
else
{
printf("no errors.\n");
 }
 Py_XDECREF(errobj);
Py_XDECREF(errdata);
Py_XDECREF(errtraceback);

    Py_Finalize();
    return 0;
}

int main()
{
load("import numpy\n");
load("import numpy\n");
}

//output is:
// no errors
// <CRASH>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090131/89c77eba/attachment.html>


More information about the Python-list mailing list