【问题标题】:How does import work with Boost.Python from inside python files从 python 文件中导入如何与 Boost.Python 一起工作
【发布时间】:2012-03-06 07:44:26
【问题描述】:

我正在使用 Boost.Python 在我的 C++ 可执行文件中嵌入解释器并执行一些预先编写的脚本。我已经让它工作了,这样我就可以调用 python 文件中的函数,但是我想使用的 python 代码导入外部文件,这些导入失败,因为“没有名为的模块”。如果我直接从 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

【问题讨论】:

    标签: python c++ boost import boost-python


    【解决方案1】:

    事实证明,我的问题是从 C++ 中初始化时模块搜索路径设置不正确的简单情况。

    From the Python Documentation intro:

    在大多数系统上(特别是在 Unix 和 Windows 上,虽然 细节略有不同),Py_Initialize() 计算模块 基于对标准位置的最佳猜测的搜索路径 Python 解释器可执行文件,假设 Python 库是 在相对于 Python 解释器的固定位置找到 可执行。特别是,它会查找一个名为 lib/pythonX.Y 相对于可执行文件所在的父目录 在 shell 命令搜索路径( 环境变量 PATH)。

    这意味着模块搜索路径绝不会设置为指向当前工作目录,而是指向系统 python 安装文件夹。

    我的解决方案是正确设置模块搜索路径以指向当前工作目录。为此,您需要初始化 python,然后提取 sys.path 值并添加任何其他路径。如果您不喜欢,请原谅使用 boost;您应该能够轻松地看到如何替换所需的任何字符串。

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

    【讨论】:

    • 对于 Python3 将 PyString_FromString 替换为 PyBytes_FromString
    • @tammojan cmets:对于 Python3,将 PyString_FromString 替换为 PyUnicode_FromString
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2022-08-22
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2021-04-14
    • 2019-10-13
    相关资源
    最近更新 更多