2012-02-14 25 views
7

我正在使用Boost.Python將解釋器嵌入到我的C++可執行文件中,並執行一些預先編寫的腳本。我有它的工作,以便我可以調用python文件中的函數,但我想要使用的Python代碼導入外部文件,這些導入失敗,因爲'沒有命名模塊'。如果我直接從python運行腳本,那麼所有工作都按預期工作。導入如何從python文件中使用Boost.Python

所以我的問題是什麼是正在通過C++綁定運行的Python腳本導入模塊的方式是什麼?

C++代碼:

#include "boost/python.hpp" 

int main(int argc, char** argv) 
{ 
    try 
    { 
    Py_Initialize(); 
    boost::python::object test = boost::python::import("__main__"); 
    boost::python::object testDict = test.attr("__dict__"); 
    boost::python::exec_file("test.py", testDict, testDict); 

    } 
    catch(boost::python::error_already_set& e) 
    { 
    PyErr_Print(); 
    } 
return 0; 

} 

Python代碼:

import ModuleX 

回答

12

所以,事實證明,我的問題是C之內從初始化時沒有正確設置模塊搜索路徑++的簡單情況。

From the Python Documentation intro:

在大多數系統中(特別是在Unix和Windows,雖然 細節略有不同),Py_Initialize()計算基於其最佳猜測位置的模塊 搜索路徑標準 Python解釋器可執行文件,假定在相對於Python解釋器 可執行文件的固定位置找到了Python庫 。特別是,它尋找一個名爲 的目錄,相對於在shell命令搜索路徑( 環境變量PATH)中找到名爲python的可執行文件 的父目錄的lib/pythonX.Y。

那麼這意味着模塊搜索路徑決不會指向當前工作目錄,而是指向系統python安裝文件夾。

我的解決方案是將模塊搜索路徑正確設置爲指向當前工作目錄。爲此,您需要初始化python,然後提取sys.path值並添加其他路徑。如果你不這樣做,請不要使用助推;你應該能夠很容易地看到如何替換所需的任何字符串。

Py_Initialize(); 

// now time to insert the current working directory into the python path so module search can take advantage 
// this must happen after python has been initialised 
boost::filesystem::path workingDir = boost::filesystem::absolute("./").normalize(); 
PyObject* sysPath = PySys_GetObject("path"); 
PyList_Insert(sysPath, 0, PyString_FromString(workingDir.string().c_str())); 
+0

對於Python3,將'PyString_FromString'替換爲'PyBytes_FromString' – schuess 2017-07-01 02:17:50

相關問題