2

I'm trying to call a python function inside my c++

When i import my python module it gives this error:

ModuleNotFoundError: No module named 'test'

Here is how i'm importing the module:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main()
{
    Py_Initialize();

    PyObject *pName = PyUnicode_FromString("test");
    PyObject *pModule = PyImport_Import(pName);

    if (pModule == nullptr)
    {
        PyErr_Print();
        std::exit(1);
    }

    Py_Finalize();

    return 0;
}

I feel like this must have to do with my project structure. It currently looks like this:

project
|-- main.cpp
|-- test.py

I'm not sure if it's worth mentioning, but the executable is in the same directory, and it's being run from that directory aswell.

How can i fix this?

dwib
  • 583
  • 4
  • 19

3 Answers3

1

This was solved by setting the "PYTHONPATH" environment variable:

setenv("PYTHONPATH", ".", 1);

Thanks @Botje

dwib
  • 583
  • 4
  • 19
1

Use Py_SetPath before Py_Initialize() to set the sys.path.

Here is a longer list of what can be done before you initialize the interpreter: pre-init-safe

Isolate the embedded Python interpreter and set the path properly to avoid problems with partially using the modules of the installed Python version.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
0

As dwib mentioned I was able to overcome by the error by setting the PYTHONPATH variable in my zshrc (may be bashrc for you) file.

export PYTHONPATH=$PATH:/home/jk/jk/c

where /home/jk/jk/c is the folder where my file was residing.

Also sourced it

. ~/.zshrc