【问题标题】:How do I import a module created with pybind11 on Ubuntu如何在 Ubuntu 上导入使用 pybind11 创建的模块
【发布时间】:2018-11-14 05:42:26
【问题描述】:

我正在尝试设置一个 CMake 项目,该项目在 Ubuntu 上使用 pybind11 为其 c++ 函数创建 python 绑定。

目录结构为:

pybind_test
    arithmetic.cpp
    arithmetic.h
    bindings.h
    CMakeLists.txt
    main.cpp
    pybind11 (github repo clone)
        Repo contents (https://github.com/pybind/pybind11)

CMakeLists.txt 文件:

cmake_minimum_required(VERSION 3.10)
project(pybind_test)

set(CMAKE_CXX_STANDARD 17)

find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(pybind11/include/pybind11)

add_executable(pybind_test main.cpp arithmetic.cpp)

add_subdirectory(pybind11)
pybind11_add_module(arithmetic arithmetic.cpp)

target_link_libraries(pybind_test ${PYTHON_LIBRARIES})

存储库构建成功并生成文件arithmetic.cpython-36m-x86_64-linux-gnu.so。如何将此共享对象文件导入 python?

pybind11 文档中的文档有这一行

$ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`

但我想使用 CMake 进行构建,而且我也不想在每次运行 python 来使用这个模块时都指定额外的包含目录。

我如何将这个共享对象文件像普通的 python 模块一样导入 python?

我使用的是 Ubuntu 16.04。

【问题讨论】:

    标签: python c++ linux cmake pybind11


    【解决方案1】:

    如果您打开终端,请转到arithmetic.cpython-36m-x86_64-linux-gnu.so 所在的目录并运行python,然后运行import arithmetic,该模块将像任何其他模块一样被导入。

    另一种选择是使用方法

    import sys
    
    sys.path.insert(0, 'path/to/directory/where/so-file/is')
    import arithmetic
    

    通过这种方法,您可以使用相对路径和绝对路径。

    【讨论】:

    • 这将导致: Traceback(最近一次调用最后一次):文件“”,第 1 行,在 中 ImportError:没有名为算术的模块
    • 好的,我通过确保绑定宏中的模块名称与 CMakeLists.txt 文件中的模块名称匹配来解决此问题。
    【解决方案2】:

    除了@super 提供的在 Python 脚本中设置路径的解决方案,您还有两个通用的解决方案。

    设置 PYTHONPATH

    在 Linux(和 macOS)中有一个名为 PYTHONPATHenvironment variable。如果在调用 Python 之前将包含 *.so 的路径添加到 PYTHONPATH,Python 将能够找到您的库。

    为此:

    export PYTHONPATH="/path/that/contains/your/so":"${PYTHONPATH}"
    

    要为每个会话“自动”应用此功能,您可以将此行添加到 ~/.bash_profile~/.bashrc(参见相同的参考资料)。在这种情况下,Python 将始终能够找到您的库。

    将你的路径复制到 Python 路径中已有的路径

    您还可以“安装”该库。通常的方法是创建一个setup.py 文件。如果设置正确,您可以使用

    构建和安装您的库
    python setup.py build
    python setup.py install
    

    (Python 会知道将您的库放在哪里。您可以使用 --user 之类的选项“自定义”一点以使用您的主文件夹,但这似乎对您来说并不特别感兴趣。)

    问题依旧:setup.py怎么写?对于您的情况,您实际上可以调用 CMake。事实上,有一个例子可以做到这一点:pybind/cmake_example。你基本上可以从那里复制粘贴。

    【讨论】:

    • 我个人将 CMake 接口包含在 Python library 中,我从我的大多数项目中调用它。
    猜你喜欢
    • 2022-12-02
    • 2023-02-26
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2015-06-23
    • 2016-08-26
    相关资源
    最近更新 更多