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

如何使用scikit-build打包含嵌套模块的Python项目?

问题解决:scikit-build打包含子包的Python项目时模块找不到

问题根源

你的CMake安装路径配置错误,导致编译后的C++模块被安装到了错误的位置;同时当存在hello.OtherModule子包时,setuptools与scikit-build的路径处理逻辑冲突,最终Python无法识别hello主包。

具体来说,CMakeLists.txt中install(TARGETS example LIBRARY DESTINATION src/hello)指定的是源码结构中的路径,但安装后Python包的结构是直接将hello目录放置在site-packages下,而非嵌套在src目录里。

解决方案

1. 修正CMakeLists.txt的安装路径

将CMake中的安装目标路径改为包的实际安装位置:

cmake_minimum_required(VERSION 3.4...3.22)

project(hello)

find_package(pybind11 CONFIG REQUIRED)

pybind11_add_module(example src/hello/hello.cpp)
# 修改DESTINATION为hello,对应site-packages下的hello包目录
install(TARGETS example LIBRARY DESTINATION hello)

2. 确保setup.py正确识别所有包

虽然find_packages('src')理论上能自动识别hello和hello.OtherModule,但可以显式添加包含规则避免遗漏:

from skbuild import setup
from setuptools import find_packages

setup(
    name="hello-cpp",
    version='0.0.1',
    description="a minimal example package (cpp version)",
    author="Me",
    license="MIT",
    # 显式包含hello主包及其所有子包
    packages=find_packages('src', include=['hello', 'hello.*']),
    package_dir={'': 'src'},
    python_requires=">=3.7",
    zip_safe=False,
)

3. 重新安装项目

在conda环境中执行:

pip install -e .

验证

运行以下命令测试:

# 测试C++模块
python -c "from hello import example; print(example.add(1, 2))"
# 测试子包
python -c "from hello import OtherModule; print('OtherModule 加载成功')"

正常情况下,第一个命令会输出3,第二个命令会输出OtherModule 加载成功,说明包结构和模块都已正确安装。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:34:59