如何通过诗歌构建 C 扩展?

thi*_*ybk 5 python python-c-api python-poetry

要构建一个由poetry我管理的 python 项目,我需要先构建 C 扩展(相当于python setup.py build)。poetry能够根据这个github 问题来做到这一点。但是对我来说pyproject.toml,在使用poetry build?

thi*_*ybk 8

添加build.py到存储库根目录。例如,如果有 1 个头文件目录和 2 个源文件:

from distutils.command.build_ext import build_ext


ext_modules = [
    Extension("<module-path-imported-into-python>",
              include_dirs=["<header-file-directory>"],
              sources=["<source-file-0>", "<source-file-1>"],
             ),
]


class BuildFailed(Exception):
    pass


class ExtBuilder(build_ext):

    def run(self):
        try:
            build_ext.run(self)
        except (DistutilsPlatformError, FileNotFoundError):
            raise BuildFailed('File not found. Could not compile C extension.')

    def build_extension(self, ext):
        try:
            build_ext.build_extension(self, ext)
        except (CCompilerError, DistutilsExecError, DistutilsPlatformError, ValueError):
            raise BuildFailed('Could not compile C extension.')


def build(setup_kwargs):
    """
    This function is mandatory in order to build the extensions.
    """
    setup_kwargs.update(
        {"ext_modules": ext_modules, "cmdclass": {"build_ext": ExtBuilder}}
    )
Run Code Online (Sandbox Code Playgroud)

添加pyproject.toml

[tool.poetry]
build = "build.py"
Run Code Online (Sandbox Code Playgroud)

要构建扩展,请执行poetry build.

有关示例,请参阅此 PR

  • 它缺少一个导入语句,以防止扩展构建失败时应该引发的错误“from distutils.errors import DistutilsPlatformError, CCompilerError, DistutilsExecError, DistutilsPlatformError” (2认同)