boost python如何在导入的python文件中导入py

时间:2017-10-10 14:50:50

标签: python c++ boost boost-python

在我的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();

但我想在strategy.py中导入一些自定义的py文件:

from model import Model

当我运行./main时,它会出错:

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

当我在没有boost python的情况下测试strategy.py时,导入效果很好,我该如何解决?

1 个答案:

答案 0 :(得分:0)

感谢Dan,我最终得到类似的东西来自动将当前目录复制到系统路径中:

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

getDir()函数:

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);
}