添加极简pyproject.toml后Python构建静默失败,求排查
使用scikit-build+pybind11构建包时
pip install -e .未实际构建导致导入失败的问题排查 我基于scikit-build的cpp示例仓库搭建了一个使用pybind11和scikit-build的极简Python包仓库。执行pip install -e .时,pip提示“安装成功”但实际并未完成C++模块的构建(怀疑setup.py中的setup函数未被执行),尝试导入模块时触发错误:
ImportError: cannot import name 'example' from 'hello'
以下两种方式可正常完成构建并导入:
- 直接执行
python setup.py develop(推测该方式绕过了pyproject.toml),但需预先通过conda install安装对应版本的setuptools、scikit-build、cmake、pybind11和ninja。 - 删除项目根目录下的pyproject.toml文件,依赖本地预安装的构建时依赖执行
pip install -e .。
我未发现pyproject.toml存在明显问题,恳请帮忙排查原因。
项目结构
hello-cpp ├── hello │ ├── __init__.py (空文件) │ └── hello.cpp ├── CMakeLists.txt ├── pyproject.toml └── setup.py
各文件内容
setup.py
from skbuild import setup setup( name="hello-cpp", version="1.2.3", description="a minimal example package (cpp version)", author="Me", license="MIT", packages=["hello"], python_requires=">=3.7", )
CMakeLists.txt
cmake_minimum_required(VERSION 3.4...3.22) project(hello) find_package(pybind11 CONFIG REQUIRED) pybind11_add_module(example hello/hello.cpp) install(TARGETS example LIBRARY DESTINATION hello)
pyproject.toml(即使不限制版本问题仍存在)
[build-system] requires = ["setuptools==65.6.3", "scikit-build==0.15.0", "cmake>=3.18", "pybind11==2.9.1", "ninja" ] build-backend = "setuptools.build_meta"
hello/hello.cpp
#include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &add, "A function that adds two numbers"); }
测试环境与补充说明
- 测试环境:Ubuntu 20
- 测试场景:
- 仅安装Python 3.10(及默认依赖)的conda环境中构建
- 预先通过conda安装所有构建依赖后构建
- 触发导入错误的测试命令:
python -c "from hello import example"
内容的提问来源于stack exchange,提问作者polortiz40
相关产品推荐
相关产品推荐

