pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
pybind11: AttributeError: module 'XXX' has no attribute 'YYY' when trying to run function from py file
我正在尝试从可执行文件所在的同一文件夹中的文件 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
重命名为不太常用的名称。
我编译了您的代码,输出符合预期。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 尝试导入pybind-opencv模块时出现libgtk错误
- C++概念:如何使用'concept'检查模板化结构的属性?
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 通过指向指针数组的指针访问子类的属性
- MSVC是否支持C++11样式的属性而不是__declspec
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 类的C++属性似乎已重新初始化
- Qt Quick-如何仅从c++代码与qml属性交互
- 为什么当我解模块化时,这个C++代代码"效率较低"?
- 用概念检查属性的类型
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- C++如何将同一类的实例作为属性
- 内联如何影响模块接口中的成员函数
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- cc_prebuilt_library_shared模块无法识别的属性"cflags"
- Python - OpenCV 模块缺少属性CV_CALIB_FIX_INTRINSIC
- GNU Radio OOT 模块属性错误:"模块"对象没有属性"MME_cpp"
- 属性错误:"模块"对象没有属性"func",仅通过C++调用
- SWIG:"模块"对象没有属性"Decklist"