提升 Python 如何在导入的 Python 文件中导入 py

boost python how to import py in imported python file

本文关键字:导入 Python 文件 py 提升      更新时间:2023-10-16

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

但我想导入一些自定义的 py 文件,strategy.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 时,导入运行良好,我该如何解决它?

感谢 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] = ''; 
    return std::string(cCurrentPath);
}