2017-10-10 82 views
0

在我的main.cpp:升压蟒蛇如何导入PY进口Python文件

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 

当我测试没有提升蟒蛇进口行之有效strategy.py,我该如何解决?

+0

也许你需要补充的位置这些.py文件到'sys.path'? –

+0

我在想同样的事情,问题是,如果我将这些文件复制到其他电脑,他们将不得不手动将它们复制到sys.path中以及 –

+0

我有某种考虑AUTOMAGIC解决方案。你能详细说明你打算如何制定这个计划吗?显然有一些二进制文件,即strategy.py脚本,然后是那些依赖关系? |例如,在我的一个嵌入python的应用程序中,我在配置中传递根脚本目录和主脚本名称,然后在导入main之前运行[this](https://pastebin.com/5Y85yd0J)之类的东西脚本使用简单的'bp :: import(name.c_str())'(它本身导入位于脚本目录中的许多依赖关系)。 –

回答

0

由于丹,我结束了这样的自动当前目录复制到系统路径:

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