python 使用setuptools沿着存根文件打包C++扩展

ukxgm1gy  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(79)

因此,我有以下文件结构:

project/
├─ cpp_src/
│  ├─ src/
│  │  ├─ cpp source files
│  ├─ test/
│  │  ├─ cpp test files
│  ├─ CMakeLists.txt
│  ├─ stub.pyi
├─ python_src/
│  ├─ ...
├─ build.py

字符串
在我的build.py文件中,我使用setuptools编译并打包了cpp_src中的C++扩展,使用了一个自定义的build_ext命令。但是,我似乎无法让它包含存根文件stub.pyi。我该如何修改setuptools命令来实现这一点?我不太关心文件结构,所以如果cpp_src中需要另一个setup.py文件,那很好。
我也在使用Poetry来管理虚拟环境,如果这有帮助的话。此外,如果有另一个构建系统可以让这个更容易,我很乐意使用。
谢谢.
编辑:这是一个build.py文件的精简版本(完整的repo在这里https://github.com/Aspect1103/Hades/tree/generation-rust):

import subprocess
from pathlib import Path
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext

class CMakeBuild(build_ext):
    def build_extension(self, ext: Extension) -> None:
        # Determine where the extension should be transferred to after it has been
        # compiled
        current_dir = Path.cwd()
        build_dir = current_dir.joinpath(self.get_ext_fullpath(ext.name)).parent

        # Determine the profile to build the CMake extension with
        profile = "Release"

        # Make sure the build directory exists
        build_temp = Path(self.build_temp).joinpath(ext.name)
        if not build_temp.exists():
            build_temp.mkdir(parents=True)

        # Compile and build the CMake extension
        subprocess.run(
            [
                "cmake",
                current_dir.joinpath(ext.sources[0]),
                f"-DDO_TESTS=false",
                f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{profile.upper()}={build_dir}",
            ],
            cwd=build_temp,
            check=True,
        )
        subprocess.run(
            ["cmake", "--build", ".", f"--config {profile}"], cwd=build_temp, check=True
        )

def main():
    setup(
        name="hades_extensions",
        script_args=["bdist_wheel"],
        ext_modules=[Extension("hades_extensions", ["cpp_src"])],
        cmdclass={"build_ext": CMakeBuild},
    )

if __name__ == "__main__":
    main()

r1zhe5dt

r1zhe5dt1#

我不相信目前有一种方法可以在文件结构中直接安装.so文件,但是你可以利用PEP 561的仅支持JavaScript的包在repo中创建一个单独的包,其中只包含你的存根,然后它将被安装并被兼容的IDE识别。

  • 在仓库中创建一个新目录,必须专门命名为my_pkg-stubs(根据PEP 561)
  • my_pkg.pyimy_pkg-stubs/__init__.pyi
  • 在您的setup.py中,添加my_pkg-stubs包,并确保.pyi文件将包含在发行版中:
...
    packages=[..., 'my_pkg-stubs'],
    include_package_data=True,
    package_data={"my_pkg-stubs": ["*.pyi"]},
...

字符串
my_pkgmy_pkg-stubs都安装时,符合PEP 561的IDE将在my_pkg-stubs中查找类型提示,并自动显示它们。我已经在应用此过程的repo上使用Visual Studio Code验证了此行为。

相关问题