Simple pybind11 module fails with No module named
Asked Answered
B

2

7

I've created a python binding for one of my projects a while back and just now wanted to pick it up again. The binding was no longer working as python was no longer able to import it - this all was working fine back then.

I've then decided to break it down to the simplest possible example:

binding.cpp

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(TestBinding, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

    m.def("add", &add, "A function which adds two numbers");
}

CMakeLists.txt:

cmake_minimum_required( VERSION 3.2 )

project(TestBinding)

add_subdirectory(pybind11)  # or find_package(pybind11)

pybind11_add_module(TestBinding binding.cpp)

# Configure project to inject source path as include directory on dependent projects
target_include_directories( TestBinding
    INTERFACE
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/pybind11/include/> )

set_target_properties( TestBinding
  PROPERTIES
  CXX_STANDARD 17
  CXX_STANDARD_REQUIRED ON
  PREFIX ""
  SUFFIX ".so"
)

Then I have a very simple test.py file which goes like this:

sys.path.insert(0, "/path/to/so/lib/")
from TestBinding import *

...which once executed always gives me the following error:

    from TestBinding import *
ModuleNotFoundError: No module named 'TestBinding'

I have literally no idea anymore what in the world could have changed from when it worked just fine and now.

Here are some more informations about my working environment:

  • Windows 10
  • Visual Studio 15 2017 Win64
  • Python 3.7 (also tried 3.5 and 3.6)

Am I missing anything really obvious?

Bedwell answered 11/11, 2019 at 4:47 Comment(0)
C
3

I have the same problem as you. After checking, it is found that the problem is caused by the inconsistency between the python version of pybind11 and the python version of the local environment. My problem was solved when I adjusted to the same python version.

Camelopardus answered 12/1, 2023 at 2:55 Comment(2)
Can you please tell how you resolved that? how can I check pybind11's version of python and how can I point it to use my default anaconda version?Thain
Usually, the .so file name you generate will have the python version. For example, my file name is pasr.cpython-38-x86 _ 64-Linux-gnu.so.Camelopardus
B
1

I've been able to resolve this by removing the SUFFIX ".so" rule from my CMakeLists.txt. This was needed back when I've initially created my bindings, but it no longer is apparently.

Bedwell answered 11/11, 2019 at 5:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.