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

ukxgm1gy  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(178)

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

  1. project/
  2. ├─ cpp_src/
  3. ├─ src/
  4. ├─ cpp source files
  5. ├─ test/
  6. ├─ cpp test files
  7. ├─ CMakeLists.txt
  8. ├─ stub.pyi
  9. ├─ python_src/
  10. ├─ ...
  11. ├─ 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):

  1. import subprocess
  2. from pathlib import Path
  3. from setuptools import Extension, setup
  4. from setuptools.command.build_ext import build_ext
  5. class CMakeBuild(build_ext):
  6. def build_extension(self, ext: Extension) -> None:
  7. # Determine where the extension should be transferred to after it has been
  8. # compiled
  9. current_dir = Path.cwd()
  10. build_dir = current_dir.joinpath(self.get_ext_fullpath(ext.name)).parent
  11. # Determine the profile to build the CMake extension with
  12. profile = "Release"
  13. # Make sure the build directory exists
  14. build_temp = Path(self.build_temp).joinpath(ext.name)
  15. if not build_temp.exists():
  16. build_temp.mkdir(parents=True)
  17. # Compile and build the CMake extension
  18. subprocess.run(
  19. [
  20. "cmake",
  21. current_dir.joinpath(ext.sources[0]),
  22. f"-DDO_TESTS=false",
  23. f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{profile.upper()}={build_dir}",
  24. ],
  25. cwd=build_temp,
  26. check=True,
  27. )
  28. subprocess.run(
  29. ["cmake", "--build", ".", f"--config {profile}"], cwd=build_temp, check=True
  30. )
  31. def main():
  32. setup(
  33. name="hades_extensions",
  34. script_args=["bdist_wheel"],
  35. ext_modules=[Extension("hades_extensions", ["cpp_src"])],
  36. cmdclass={"build_ext": CMakeBuild},
  37. )
  38. if __name__ == "__main__":
  39. 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文件将包含在发行版中:
  1. ...
  2. packages=[..., 'my_pkg-stubs'],
  3. include_package_data=True,
  4. package_data={"my_pkg-stubs": ["*.pyi"]},
  5. ...

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

相关问题