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

How to build C extensions via poetry?

要构建由 poetry 管理的 python 项目,我需要先构建 C 扩展(相当于 python setup.py build)。 poetry照着这个github issue就可以了。但对我来说,不清楚在使用 poetry build?

构建时执行 C 扩展构建的 pyproject.toml 中包含什么

build.py 添加到 repo-root。例如。如果有一个头文件目录和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}}
    )

添加到 pyproject.toml:

[tool.poetry]
build = "build.py"

构建扩展执行poetry build.

示例参考this PR