pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'

pybind11: AttributeError: module 'XXX' has no attribute 'YYY' when trying to run function from py file

本文关键字:属性 模块 YYY XXX 函数 错误 py pybind11 运行 文件      更新时间:2023-10-16

我正在尝试从可执行文件所在的同一文件夹中的文件 test.py 启动函数z:

def z(k):
return 9.

和调用代码:

#include <iostream>
#include <pybind11/embed.h>
namespace py = pybind11;
using namespace std;
int main(){
py::scoped_interpreter guard{};
auto module = py::module::import("test");
auto resultobj = module.attr("z")(9);
py::function z =
py::reinterpret_borrow<py::function>(
py::module::import("test").attr("z")
);
py::object resulto = z(1);
double result = resulto.cast<double>();
cout << result<<endl;
return 0;
}

它像这样崩溃:

terminate called after throwing an instance of 'pybind11::error_already_set'
what():  AttributeError: module 'test' has no attribute 'z'

模块测试显然已加载,因为如果我在 C++ 中用 test1 替换 test,那么程序会以不同的方式崩溃。此外,如果我用数学和 sqrt 替换 test 和 z,它也可以工作。如何解决我的问题?

我的第一个假设是首先加载了另一个名为test的模块(隐藏您的test.py(。您可以通过添加来验证模块的完整路径

py::print(module.attr("__file__"));

如果是这种情况,您还可以将test.py重命名为不太常用的名称。

我编译了您的代码,输出符合预期。