Search code examples
pythonc++boostboost-python

boost python how to import py in imported python file


in my main.cpp:

    bp::object main     = bp::import("__main__");
    bp::object globals  = main.attr("__dict__");
    bp::object module   = import("strategy", "strategy.py", globals);
    bp::object Strategy = module.attr("Strategy");
    bp::object strategy = Strategy();

but i want to import some self defined py files, in strategy.py I have:

from model import Model

when i run ./main, it gives error:

File "strategy.py", line 2, in <module>
from model import Model
ImportError: No module named model

When I test strategy.py without boost python the import works well, how can I fix it?


Solution

  • thanks to Dan, I end up with something like this to automatically copy current directory into system path:

    bp::object sys_module = bp::import("sys"); 
    bp::str module_directory = getDir().c_str();
    sys_module.attr("path").attr("insert")(1, module_directory);
    

    getDir() function:

    std::string getDir() // get current directory path
    {
        char cCurrentPath[FILENAME_MAX];
        if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))){
            return "";
        }
        cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; 
    
        return std::string(cCurrentPath);
    }