【问题标题】:Extending setuptools with CMake. Build extension does not install使用 CMake 扩展 setuptools。构建扩展不安装
【发布时间】:2021-07-24 23:49:19
【问题描述】:

我正在尝试使用 CMake 在 setup.py 中的 this SO post 之后构建一个 fortran 扩展。

当我运行pip install . -v 时,我可以看到我的扩展程序构建得很好,但是二进制文件(.so 文件)没有与尝试导入它的 python 脚本一起安装。如何保证我的扩展程序已安装?

这是我的 setup.py 供参考

import os
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig

class CMakeExtension(Extension):
    def __init__(self, name):
        # don't invoke the original build_ext for this special extension
        super().__init__(name, sources=[])


class build_ext(build_ext_orig):
    def run(self):
        for ext in self.extensions:
            self.build_cmake(ext)
        super().run()

    def build_cmake(self, ext):
        cwd = pathlib.Path().absolute()

        # these dirs will be created in build_py, so if you don't have
        # any python sources to bundle, the dirs will be missing
        build_temp = pathlib.Path(self.build_temp)
        build_temp.mkdir(parents=True, exist_ok=True)
        extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
        extdir.mkdir(parents=True, exist_ok=True)
        
        # example of cmake args
        config = 'Debug' if self.debug else 'Release'
        cmake_args = [
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY='+str(extdir.parent.absolute()),
            '-DCMAKE_BUILD_TYPE=' + config,
            '-DBUILD_PYTHON_MODULE=ON',
            '-DBUILD_FORTRAN_LIBRARY=OFf',
            '-DBUILD_THE_EXAMPLES=OFF',
        ]
        
        # example of build args
        build_args = [
            '--config', config, 
        ]
        
        os.chdir(str(build_temp))
        self.spawn(['cmake', str(cwd)] + cmake_args)
        if not self.dry_run:
            self.spawn(['cmake', '--build', '.'] + build_args)
        # Troubleshooting: if fail on line above then delete all possible 
        # temporary CMake files including "CMakeCache.txt" in top level dir.
        os.chdir(str(cwd))


setup(name = 'mypythonlibrary',
      packages=['mypythonlibrary'],
      version='0.1',
      ext_modules=[CMakeExtension('mypythonlibrary/myfortranlibrary')],
      cmdclass={'build_ext': build_ext,})

【问题讨论】:

  • 考虑使用scikit-build 而不是手动解决方案。它原生使用 CMake。

标签: python cmake setup.py


【解决方案1】:

最好只给你skbuild。他们有 c++、cython、c 的示例。我只是整理了一些 f2py/fortran 的例子:https://github.com/Nicholaswogan/skbuild-f2py-examples

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多