Greetings The task is to call a function from the python script documentCreation.py, located in the same directory as the C ++ executable file. The code below is executed and NULL is written to the pModule variable, that is, the script is not loaded. Assumed that the directory in which the script is not included in the list of sys.path, but Py_GetPath () says the opposite. Tell me how to import the module? System windows 10, python 3.5.2

PyObject *pName, *pModule; Py_Initialize(); pName = PyUnicode_FromString("documentCreation"); pModule = PyImport_Import(pName); //проверяем системные пути python CStringA myConvertedString(Py_GetPath()); cout << myConvertedString; if (pModule == NULL) { cout << "import fail"; } Py_Finalize(); 

    1 answer 1

    Make sure that the import documentCreation works outside the C ++ program (the module does not throw errors during the import).

    The current directory is not automatically added to the pythonpath. This can be done by executing: import sys; sys.path.append('') import sys; sys.path.append('') . Here is the call-function.cc file with the C ++ code for the example:

     #include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString("import sys; sys.path.append('')\n" "import some_module;print(some_module.some_function(3,4))"); Py_Finalize(); } 

    where some_function.py file in the current directory contains:

     def some_function(a, b): return a * b 

    To build an executable file and run it on Ubuntu:

     $ g++ call-function.cc -o call-function `pkg-config --cflags --libs python3` $ ./call-function 12 

    For Windows, the commands should be corrected.

    It is not necessary to PyRun_SimpleString() , you can use PyList_Append(sys_path, program_dir) and then PyImport_Import() .

    • Thanks for the answer. If the current directory is not automatically added to the pythonpath, then why Py_GetPath (), without adding anything to sys.path, returns the string C: \ Users \ clawf \ OneDrive \ Source \ staff \ Win32 \ Debug \ python35_d.zip; C : \ Program Files (x86) \ Python35-32 \ Lib \; C: \ Program Files (x86) \ Python35-32 \ DLLs \; C: \ Users \ clawf \ OneDrive \ Source \ staff \ Win32 \ Debug where is the last path Is this the current directory with the C ++ executable and the module being imported? - Wickedwannabe
    • @Wickedwannabe 1- Does the code from my answer work as it is on your machine? 2- "where does the X folder get into sys.path" when python embedded — this may be a good separate question. Create a minimal but complete (as in my answer) sample code, run it from different folders, make sure that in your case the current working directory is added every time and publish it as a new Stack Overflow question. - jfs