You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pybind11嵌入Python时出现lidar模块NotFoundError求助

问题:嵌入Python时无法导入同目录自定义模块

我通过C++嵌入运行Python项目,此前能成功运行简单Python文件,但当前项目运行报错:Python项目的main.py包含from lidar import some_function语句,lidar.py与main.py处于同一目录,单独运行Python项目正常,但嵌入运行时触发ModuleNotFoundError。

终端报错信息

Hello, World!
terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  ModuleNotFoundError: No module named 'lidar'

At:
  /radar-imaging-dataset/brateesh/pybind_example2/src/cpp/shenron_package-main/main.py(8): <module>

Aborted (core dumped)

我的C++代码

#include "additionals/pybind11/include/pybind11/pybind11.h"
#include "additionals/pybind11/include/pybind11/embed.h"
#include "additionals/pybind11/include/pybind11/eval.h"
#include <iostream>

namespace py = pybind11;

int main() {
  //std::cout << "Current Working Directory: " << std::filesystem::current_path() << std::endl;
  py::scoped_interpreter guard{};
  py::print("Hello, World!");
  py::object scope = py::module_::import("__main__").attr("__dict__");
  py::eval_file("/radar-imaging-dataset/brateesh/pybind_example2/src/cpp/shenron_package-main/main.py", scope);
  //py::eval_file("arr.py", scope);
  
  return 0;
}
解决方案

问题核心是:单独运行Python脚本时,解释器会自动将脚本所在目录加入模块搜索路径sys.path,但嵌入模式下不会自动添加,导致找不到同目录的自定义模块。以下是三种可行解决方法:

  • 方法1:在C++中手动添加路径到sys.path
    在调用eval_file前,将main.py所在目录添加到Python的模块搜索路径:

    // 定义main.py所在目录的绝对路径
    std::string py_script_dir = "/radar-imaging-dataset/brateesh/pybind_example2/src/cpp/shenron_package-main/";
    // 导入sys模块
    py::module_ sys_module = py::module_::import("sys");
    // 将目标目录追加到sys.path
    sys_module.attr("path").attr("append")(py_script_dir);
    

    把这段代码插入到py::eval_file之前即可。

  • 方法2:在Python代码中添加路径
    在main.py的最开头添加以下代码,确保脚本所在目录被加入搜索路径:

    import sys
    import os
    # 获取当前脚本所在目录并添加到sys.path
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    
  • 方法3:切换C++进程的工作目录
    在启动Python解释器前,将C++进程的工作目录切换到main.py所在目录,这样Python会自动将当前工作目录加入sys.path:

    #include <filesystem>
    // ...
    int main() {
      // 切换工作目录到main.py所在路径
      std::filesystem::current_path("/radar-imaging-dataset/brateesh/pybind_example2/src/cpp/shenron_package-main/");
      py::scoped_interpreter guard{};
      py::print("Hello, World!");
      py::object scope = py::module_::import("__main__").attr("__dict__");
      // 此时可以使用相对路径加载main.py
      py::eval_file("main.py", scope);
      
      return 0;
    }
    

    注意需要包含<filesystem>头文件,且编译器需支持C++17及以上标准。

内容的提问来源于stack exchange,提问作者brex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:43:11