Python pybind11模块目录
我正在使用pybind11编写一个python模块,它将成为一个库Python pybind11模块目录,python,c++,pybind11,Python,C++,Pybind11,我正在使用pybind11编写一个python模块,它将成为一个库 在我的C++代码中的某个点,我需要知道My.S./DLL模块的绝对路径(我需要它来访问包含我的模块的包中的子目录中的一些文件)。 我试图通过以下方式访问\uuuuu文件\uuuuu属性: namespace py = pybind11; std::string path; std::string getPath() { return path; } PYBIND11_MODULE(mymodule, m) {
在我的C++代码中的某个点,我需要知道My.S./DLL模块的绝对路径(我需要它来访问包含我的模块的包中的子目录中的一些文件)。 我试图通过以下方式访问
\uuuuu文件\uuuuu
属性:
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);
}
有没有方法知道用pyByd11?< /p> < p>编写的模块的绝对路径。如果你只运行C++,那么你应该假设你的模块被命名为“代码>示例< /Cord>”,并且可以在python路径上找到。
#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>();
}
#包括
名称空间py=pybind11;
void getModulePath()
{
py::scoped_解释器保护{};//启动解释器并使其保持活动状态
py::object-example=py::module::import(“示例”);
返回example.attr(“_文件__”).cast();
}
如果您的应用程序是从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>();
}
#包括
名称空间py=pybind11;
void getModulePath()
{
py::gil_范围的获取;
py::object-example=py::module::import(“示例”);
返回example.attr(“_文件__”).cast();
}
这是因为我们正在使用python解释器来导入示例模块,所以
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
属性将被设置,据我的理解,\uuuuuuuuuuu。这很有意义,因为python发现模块的位置可以根据python路径高度可变。因此,如果你在C++中运行这个代码,你就需要依赖某种C++方法来找出模块位于哪里。如果您在c++17中,并且您的库与可执行文件位于同一文件夹中,那么代码>标准::文件系统::当前路径
可能是一个选项。这里的问题是没有可执行文件,因为此模块将是python库的一部分。用户可以将包含我的模块的包放在任何他想要的地方。我尝试了,但它返回的是调用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>();
}