Justin Justin -4 years ago 117
C Question

Using the python api in c not working on mac

I am trying to import my python file that is in the same directory as my main.c file but for some reason it will not work. I keeps failing at PyImport_ImportModule('dizzle'). Any help would be greatly appreciated I'm on a Mac (*I can get this to work on Ubuntu which is strange) I have PYTHONPATH set.

mytestfolder
main.c
dizzle.py


Here is my main.c

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <Python/Python.h>

int main()
{
char *xx = getpimacaddress2();
printf("%s", xx);

}

char *getpimacaddress2()
{



Py_Initialize();


PyObject* module = PyImport_ImportModule("dizzle");
assert(module != NULL);

PyObject* klass = PyObject_GetAttrString(module, "SnowTest");
assert(klass != NULL);

PyObject* instance = PyInstance_New(klass, NULL, NULL);
assert(instance != NULL);

PyObject* result = PyObject_CallMethod(instance, "add_test", "(ii)", 10, 34);
assert(result != NULL);

Py_Finalize();

return PyString_AsString(result);
}


Python file dizzle.py

class SnowTest:

def add_test(self, x, y):
z = x + y
return str(z)

Answer Source

I was able to recreate the problem. However note that I did so on Windows. The solution should be the same. I mentioned in the comments that it could be something with sys.path. Which after testing actually was the problem.

Right after calling Py_Initialize() do the following:

PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("..."));

Where you replace ... with something that retrieves your application's current working directory (Which in your case would be the directory containing the dizzle.py file).

You can also check:

PyRun_SimpleString("print(os.getcwd())");

If it prints the current working directory of your application, then you can equally do the following right after calling Py_Initialize():

PyRun_SimpleString("sys.path.append(os.getcwd())");

Doing either of those makes assert(module != NULL) pass for me.

If it does have something to do with PYTHONPATH (which I doubt based on your error). Then you can Py_SetPythonHome(L"/path/to/python").

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download