Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyImport_Import fails (returns NULL)

Tags:

python

c

I am a newbie in python, so may be this is a silly question. I want to write simple c program with embedded python script. I have two files:

call-function.c:

    #include <Python.h>
    int main(int argc, char *argv[])
    {
        PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

        if (argc < 3)
        {
            printf("Usage: exe_name python_source function_name\n");
            return 1;
            }

        // Initialize the Python Interpreter
        Py_Initialize();

        // Build the name object
        if ((pName = PyString_FromString(argv[1])) == NULL) {
            printf("Error: PyString_FromString\n");
            return -1;
        }

        // Load the module object
        if ((pModule = PyImport_Import(pName)) == NULL) {
            printf("Error: PyImport_Import\n");
            return -1;
        }

        // pDict is a borrowed reference 
        if ((pDict = PyModule_GetDict(pModule))==NULL) {
            printf("Error: PyModule_GetDict\n");
            return -1;
        }
...

and

hello.py:

def hello():
    print ("Hello, World!")

I compile and run this as follows:

gcc -g -o call-function call-function.c -I/usr/include/python2.6 -lpython2.6
./call-function hello.py hello

and have this:

Error: PyImport_Import

i.e. PyImport_Import returns NULL. Could you help me with this issue? Any help will be appreciated.

Best wishes,

Alex

like image 444
Alexander Avatar asked Jul 08 '13 17:07

Alexander


3 Answers

I have resolved this issue by setting PYTHONPATH to pwd. Also module name (without .py) should be set for argv[1].

Thank you!

like image 139
Alexander Avatar answered Oct 16 '22 17:10

Alexander


I ran into this issue also after struggling for a while.After searching the web I found that is was a system path issue. After adding the two lines after Py_Initialize(); it worked.

OS: Windows 7, Compiler: Embarcadero C++ Builder XE6, Python: Version 2.7

Reference: C++ With Python

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"C:\\Python27\")");
like image 23
Chad Avatar answered Oct 16 '22 18:10

Chad


If the python source file is located in the working directory (i.e. where the *.cpp files of the project reside), you can use...

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

...to add the working directory to the Python path.

like image 4
Alfons Avatar answered Oct 16 '22 16:10

Alfons