我正在使用pybind11编写一个python模块,它将成为一个库。
在我的C++代码中,我需要知道我的.so/.dll模块的绝对路径(我需要它来访问包含我的模块的包中的子目录中的一些文件)。我尝试以这种方式访问__file__属性:
namespace py = pybind11;
std::string path;
std::string getPath() {
return path;
}
PYBIND11_MODULE(mymodule, m) {
path = m.attr("__file__").cast<std::string>();
//use path in some way to figure out the path the module...
m.def("get_path", &getPath);
}但是我得到了一个错误
ImportError: AttributeError: module 'mymodule' has no attribute '__file__'有没有办法知道用pybind11编写的模块的绝对路径?
发布于 2020-07-24 00:22:53
如果您仅从C++运行,则假定您的模块名为example并且可以在pythonpath路径中找到,则可以使用此方法。
#include <pybind11/embed.h>
namespace py = pybind11;
void getModulePath()
{
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
py::object example = py::module::import("example");
return example.attr("__file__").cast<std::string>();
}如果您的应用程序是从python内部运行的,我认为以下内容应该可以工作
#include <pybind11/pybind11.h>
namespace py = pybind11;
void getModulePath()
{
py::gil_scoped_acquire acquire;
py::object example = py::module::import("example");
return example.attr("__file__").cast<std::string>();
}这是因为我们使用python解释器导入示例模块,因此将设置__file__属性
https://stackoverflow.com/questions/63039814
复制相似问题