【问题标题】:boost python how to import py in imported python fileboost python如何在导入的python文件中导入py
【发布时间】:2017-10-10 14:50:50
【问题描述】:

在我的 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();

但我想在 strategy.py 中导入一些自定义的 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 时导入效果很好,我该如何修复它?

【问题讨论】:

  • 也许您需要将那些 .py 文件的位置添加到sys.path?
  • 我也在考虑同样的事情,问题是,如果我将这些文件复制到其他一些 PC,他们将不得不手动将它们复制到 sys.path 以及
  • 我想到了某种自动解决方案。您能否详细说明您打算如何布局?显然有一些二进制文件,strategy.py 脚本,然后是那些依赖项? |例如,在我的一个嵌入 python 的应用程序中,我传递了根脚本目录和配置中的主脚本名称,然后在使用简单的 bp::import(name.c_str())(它本身导入位于脚本目录中的许多依赖项)。
  • 问题是命令行解释器(python.exe)会在运行交互时自动添加脚本的路径,或者一个空字符串(导致在当前目录中搜索)。当您嵌入时,AFAICT 有责任对其进行适当设置。
  • 我明白了,谢谢 Dan,我现在知道如何正确修复它了。

标签: python c++ boost boost-python


【解决方案1】:

感谢 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] = '\0'; 

    return std::string(cCurrentPath);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多