2017-10-10 122 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); 
}