首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pybind11模块的目录

pybind11模块的目录
EN

Stack Overflow用户
提问于 2020-07-23 01:20:48
回答 1查看 723关注 0票数 1

我正在使用pybind11编写一个python模块,它将成为一个库。

在我的C++代码中,我需要知道我的.so/.dll模块的绝对路径(我需要它来访问包含我的模块的包中的子目录中的一些文件)。我尝试以这种方式访问__file__属性:

代码语言:javascript
复制
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);
}

但是我得到了一个错误

代码语言:javascript
复制
ImportError: AttributeError: module 'mymodule' has no attribute '__file__'

有没有办法知道用pybind11编写的模块的绝对路径?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-24 00:22:53

如果您仅从C++运行,则假定您的模块名为example并且可以在pythonpath路径中找到,则可以使用此方法。

代码语言:javascript
复制
#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内部运行的,我认为以下内容应该可以工作

代码语言:javascript
复制
#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__属性

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63039814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档