PyImport_Import error (returns NULL)

I'm new to python, so maybe this is a dumb question. I want to write a simple c program with a built-in 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 it like this:

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

and do the following:

 Error: PyImport_Import 

i.e. PyImport_Import returns NULL . Could you help me in this matter? Any help would be appreciated.

Best wishes,

Alex

+6
source share
4 answers

I solved this problem by installing PYTHONPATH on pwd . You must also specify the module name (without .py) for argv [1].

Thanks!

+11
source

I ran into this problem after some time. After searching the Internet, I found this to be a system path issue. After adding two lines after Py_Initialize (); he worked.

OS: Windows 7, compiler: Embarcadero C ++ Builder XE6, Python: version 2.7

Link: C ++ with Python

 Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"C:\\Python27\")"); 
+1
source

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

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

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

0
source

It works on VS-C ++, only after applying the response from the Python Call function with parameters from the C ++ project (Visual Studio) for using Python in release mode with _putenv_s ("PYTHONPATH", "<... \ myPyPath>"); before Py_Initialize () solved the problem

0
source

Source: https://habr.com/ru/post/1490340/


All Articles