Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyImport_Import cannot find module

Tags:

c++

python

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?

like image 966
dwib Avatar asked May 09 '26 06:05

dwib


1 Answers

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.

like image 186
Szabolcs Dombi Avatar answered May 10 '26 20:05

Szabolcs Dombi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!