如何通过pyproject.toml使pip install -e .编译Cython扩展?
在可编辑模式下编译Cython扩展(pyproject.toml+setuptools)
为什么pip install .执行build_ext但pip install -e .不执行?
常规安装(pip install .)会构建完整的分发包,setuptools必然触发build_ext编译扩展模块,确保分发包包含可执行的二进制文件。而默认的可编辑安装采用传统“egg-link”模式,仅创建指向源码目录的链接,跳过了完整构建流程——它假设纯Python源码可直接导入,但Cython扩展需要编译后才能被Python识别,因此默认不会执行build_ext。
解决方案
方法1:使用setuptools严格可编辑模式(推荐,setuptools≥64.0)
通过配置editable_mode = "strict"强制可编辑安装执行完整构建流程,同时调整编译路径让.so生成在本地目录:
- 修改
pyproject.toml添加严格模式配置:
[tool.setuptools] package-dir = {"" = "."} editable_mode = "strict" # 启用严格可编辑模式 packages.find = {} cmdclass.build_ext = "_custom_build.build_ext"
- 调整自定义
build_ext类,重写路径逻辑让.so生成在源码对应目录:
from setuptools import Extension from setuptools.command.build_ext import build_ext as _build_ext from Cython.Build import cythonize import os class build_ext(_build_ext): def initialize_options(self): super().initialize_options() if self.distribution.ext_modules is None: self.distribution.ext_modules = [] extensions = Extension(...) # 你的扩展配置 self.distribution.ext_modules.extend(cythonize(extensions)) def build_extensions(self): # 你的自定义编译逻辑 super().build_extensions() def get_ext_full_path(self, ext_name): # 让编译后的.so直接生成在源码包目录下 ext_path = ext_name.split('.') ext_path[-1] = self.get_ext_filename(ext_path[-1]) return os.path.join(*ext_path)
执行pip install -e .后,编译好的.so会直接出现在项目的包目录中,同时完成常规可编辑安装的所有步骤。
方法2:自定义PEP 660可编辑构建钩子(灵活定制)
如果需要更精细的控制,可实现PEP 660定义的build_wheel_for_editable钩子,手动触发build_ext并处理文件复制:
- 创建自定义构建后端文件
backend.py:
from setuptools.build_meta import * from setuptools.command.build_ext import build_ext import os import shutil def build_wheel_for_editable(wheel_directory, config_settings=None, metadata_directory=None): # 先执行默认的可编辑wheel构建流程 wheel_path = build_wheel_for_editable.__wrapped__(wheel_directory, config_settings, metadata_directory) # 初始化并运行自定义build_ext from setuptools import Distribution dist = Distribution() cmd = build_ext(dist) cmd.initialize_options() cmd.finalize_options() cmd.run() # 将编译后的.so复制到项目本地目录(根据包结构调整路径) build_lib = cmd.build_lib for root, dirs, files in os.walk(build_lib): for file in files: if file.endswith('.so'): rel_path = os.path.relpath(root, build_lib) target_dir = os.path.join('.', rel_path) os.makedirs(target_dir, exist_ok=True) shutil.copy2(os.path.join(root, file), target_dir) return wheel_path
- 修改
pyproject.toml的构建后端指向自定义模块:
[build-system] requires = ["setuptools>=61.0", "numpy>=1.17", "cython>=0.18"] build-backend = "backend" [tool.setuptools] package-dir = {"" = "."} packages.find = {} cmdclass.build_ext = "_custom_build.build_ext"
验证
执行pip install -e .后,检查项目目录下是否生成目标.so文件,在Python交互环境中导入你的包,确认扩展模块可正常调用。
内容的提问来源于stack exchange,提问作者Silmathoron
相关产品推荐
相关产品推荐

