2

This is a very basic question, but it has me stumped.

I am trying to embed some scipy routines into a c-program. However, I am unable to successfully complete the initial step of importing any scipy modules.

I can import the top-level of scipy, without getting a null return value, so I'm pretty sure the install is not a problem...

PyObject *pckg_name, *pckg;

pckg_name = PyString_FromString("scipy");
pckg = PyImport_Import(pckg_name);
if (!pckg)
{
        printf("Error importing python module %s.\n");
        return;
} 

...but I am unable to get to any lower level. I've tried all kinds of combinations with PyImport_Import and PyImport_ImportModule, e.g. importing "scipy.stats" as step 1, or importing stats as step 2 after importing scipy, but nothing is working.

I am able to import and use functions from the "random" module, so I don't think there's a problem with my base Python install. I know I'm missing something obvious here, but I can't figure out what it is.

1 Answers1

4

For what it's worth, this works for me:

try_scipy.c

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

int main(int argc, char *argv[])
{
    PyObject *pckg_name;
    PyObject *pckg;

    Py_Initialize();

    pckg_name = PyString_FromString("scipy.stats");
    pckg = PyImport_Import(pckg_name);
    if (!pckg) {
        printf("fail\n");
    }
    else {
        printf("got it!\n");
        Py_DECREF(pckg);
    }
    Py_DECREF(pckg_name);

    Py_Finalize();

    return EXIT_SUCCESS;
}

Compile and run:

$ gcc try_scipy.c `python-config --cflags --ldflags` -o try_scipy
$ ./try_scipy
got it!
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • I've tried importing scipy.stats (and also scipy.stats.beta) using PyImport_Import as my first step, and a null is always returned. If this is supposed to work, I'd be inclined to suspect a problem with the install, but I can't figure out what kind of problem would let me load scipy, but not scipy.stats. – NaiveBayesian Jul 26 '14 at 03:20
  • Can you import scipy.stats in a python script? – Warren Weckesser Jul 26 '14 at 03:23
  • Good suggestion (that I should have tried earlier); it's at least isolated my problem. When I put `from scipy import stats` at the top of a working python script I have, the result was an error message that said `numpy.ufunc has the wrong size, try recompiling`. So it looks like there's a very strong possibility that the problem is in my install, and not in my c-program. Thanks. – NaiveBayesian Jul 26 '14 at 13:29