lon*_*ver 17 c++ python packaging cmake setuptools
我正在编写一个链接C++库的Python扩展,我正在使用cmake来帮助构建过程.这意味着,现在,我知道如何捆绑它的唯一方法,我必须先用cmake编译它们才能运行setup.py bdist_wheel.肯定有更好的办法.
我想知道是否有可能(或任何人尝试过)调用CMake作为setup.py ext_modules构建过程的一部分?我猜有一种方法来创建一个东西的子类但我不知道在哪里看.
我正在使用CMake,因为它为我提供了更多的控制,可以根据我的需要构建具有复杂构建步骤的c和c ++库扩展.另外,我可以使用findPythonLibs.cmake中的PYTHON_ADD_MODULE()命令直接使用cmake构建Python扩展.我只希望这一步都是一步.
hoe*_*ing 19
您基本上需要做的是覆盖您的build_ext命令类setup.py并在命令类中注册它.在您的自定义impl中build_ext,配置并调用cmake以配置然后构建扩展模块.不幸的是,官方文档对于如何实现自定义distutils命令非常简洁(参见Extending Distutils); 我发现直接研究命令代码会更有帮助.例如,以下是该build_ext命令的源代码.
我准备了一个简单的项目,包括一个C扩展foo和一个python模块spam.eggs:
so-42585210/
??? spam
? ??? __init__.py # empty
? ??? eggs.py
? ??? foo.c
? ??? foo.h
??? CMakeLists.txt
??? setup.py
Run Code Online (Sandbox Code Playgroud)
这些只是我为测试安装脚本而编写的一些简单存根.
spam/eggs.py (仅用于测试库调用):
from ctypes import cdll
import pathlib
def wrap_bar():
foo = cdll.LoadLibrary(str(pathlib.Path(__file__).with_name('libfoo.dylib')))
return foo.bar()
Run Code Online (Sandbox Code Playgroud)
spam/foo.c:
#include "foo.h"
int bar() {
return 42;
}
Run Code Online (Sandbox Code Playgroud)
spam/foo.h:
#ifndef __FOO_H__
#define __FOO_H__
int bar();
#endif
Run Code Online (Sandbox Code Playgroud)
CMakeLists.txt:
cmake_minimum_required(VERSION 3.10.1)
project(spam)
set(src "spam")
set(foo_src "spam/foo.c")
add_library(foo SHARED ${foo_src})
Run Code Online (Sandbox Code Playgroud)
这就是魔术发生的地方.当然,还有改进的空间很大-你可以通过额外的选项CMakeExtension,如果你需要(有关扩展的更多信息,请参阅类大厦C和C++扩展),使CMake的选项配置通过setup.cfg通过重写方法initialize_options和finalize_options等.
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
]
# example of build args
build_args = [
'--config', config,
'--', '-j4'
]
os.chdir(str(build_temp))
self.spawn(['cmake', str(cwd)] + cmake_args)
if not self.dry_run:
self.spawn(['cmake', '--build', '.'] + build_args)
os.chdir(str(cwd))
setup(
name='spam',
version='0.1',
packages=['spam'],
ext_modules=[CMakeExtension('spam/foo')],
cmdclass={
'build_ext': build_ext,
}
)
Run Code Online (Sandbox Code Playgroud)
构建项目的轮子,安装它.测试库已安装:
$ pip show -f spam
Name: spam
Version: 0.1
Summary: UNKNOWN
Home-page: UNKNOWN
Author: UNKNOWN
Author-email: UNKNOWN
License: UNKNOWN
Location: /Users/hoefling/.virtualenvs/stackoverflow/lib/python3.6/site-packages
Requires:
Files:
spam-0.1.dist-info/DESCRIPTION.rst
spam-0.1.dist-info/INSTALLER
spam-0.1.dist-info/METADATA
spam-0.1.dist-info/RECORD
spam-0.1.dist-info/WHEEL
spam-0.1.dist-info/metadata.json
spam-0.1.dist-info/top_level.txt
spam/__init__.py
spam/__pycache__/__init__.cpython-36.pyc
spam/__pycache__/eggs.cpython-36.pyc
spam/eggs.py
spam/libfoo.dylib
Run Code Online (Sandbox Code Playgroud)
从spam.eggs模块运行包装函数:
$ python -c "from spam import eggs; print(eggs.wrap_bar())"
42
Run Code Online (Sandbox Code Playgroud)
小智 8
我想补充一下我自己的答案,作为霍夫林描述的一种附录.
谢谢,hoefling,因为你的回答帮助我按照与我自己的存储库大致相同的方式编写安装脚本.
写这个答案的主要动机是试图将缺失的部分"粘合在一起".OP没有说明正在开发的C/C++ Python模块的性质; 我想在前面说清楚以下步骤是针对C/C++ cmake构建链创建多个.dll/ .so文件以及预编译*.pyd/ so文件以及.py需要放在脚本目录中的一些通用文件.
所有这些文件在运行cmake build命令后直接生效...有趣.没有建议以这种方式构建setup.py.
因为setup.py意味着你的脚本将成为你的包/库的一部分,并且.dll必须通过库部分声明需要构建的文件,列出源和包括目录,所以没有直观的方法来告诉setuptools这是一个调用的结果库,脚本和数据文件cmake -b所发生的build_ext都应该走在他们各自的位置.更糟糕的是,如果您希望通过setuptools跟踪此模块并完全卸载,则意味着用户可以卸载它并在需要时将每条跟踪从系统中删除.
我在写一个setup.py的模块是联吡啶时,.pyd/ .so这里描述建筑搅拌机作为一个Python模块相当于:
https://wiki.blender.org/wiki//User:Ideasman42/BlenderAsPyModule(更好的说明,但现在死链接) http://www.gizmoplex.com/wordpress/compile-blender-as-python-module/(可能更糟糕的说明,但似乎仍然在线)
您可以在github上查看我的存储库:
https://github.com/TylerGubala/blenderpy
这是我写这个答案背后的动机,并希望能帮助其他人尝试完成类似的东西,而不是丢掉他们的cmake构建链,或者更糟糕的是,必须维护两个独立的构建环境.如果它不合适,我道歉.
setuptools.Extension使用我自己的类扩展类,该类不包含sources或libs属性的条目
setuptools.commands.build_ext.build_ext使用我自己的类扩展类,它有一个自定义方法,执行我必要的构建步骤(git,svn,cmake,cmake --build)
使用我自己的类来扩展distutils.command.install_data.install_data类(yuck,distutils...但是似乎没有一个类似的setuputils),以在setuptools的记录创建期间标记构建的二进制库(installed-files.txt),以便
这些库将被记录下来并将被卸载 pip
uninstall package_name
该命令py setup.py bdist_wheel也可以原生使用,可用于提供源代码的预编译版本
setuptools.command.install_lib.install_lib使用我自己的类扩展类,这将确保将构建的库从其生成的构建文件夹移动到setuptools期望它们的文件夹中(在Windows上,它将.dll文件放在bin/Release文件夹中而不是setuptools中期待它)
setuptools.command.install_scripts.install_scripts使用我自己的类扩展类,以便将脚本文件复制到正确的目录(Blender期望2.79或任何目录位于脚本位置)
执行构建步骤后,将这些文件复制到一个已知目录中,setuptools将复制到我的环境的site-packages目录中.此时,剩余的setuptools和distutils类可以接管写入installed-files.txt记录,并且可以完全删除!
这是一个样本,或多或少来自我的存储库,但为了更清楚的更具体的事情进行了修剪(你可以随时前往回购并自己查看)
from distutils.command.install_data import install_data
from setuptools import find_packages, setup, Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.install_lib import install_lib
from setuptools.command.install_scripts import install_scripts
import struct
BITS = struct.calcsize("P") * 8
PACKAGE_NAME = "example"
class CMakeExtension(Extension):
"""
An extension to run the cmake build
This simply overrides the base extension class so that setuptools
doesn't try to build your sources for you
"""
def __init__(self, name, sources=[]):
super().__init__(name = name, sources = sources)
class InstallCMakeLibsData(install_data):
"""
Just a wrapper to get the install data into the egg-info
Listing the installed files in the egg-info guarantees that
all of the package files will be uninstalled when the user
uninstalls your package through pip
"""
def run(self):
"""
Outfiles are the libraries that were built using cmake
"""
# There seems to be no other way to do this; I tried listing the
# libraries during the execution of the InstallCMakeLibs.run() but
# setuptools never tracked them, seems like setuptools wants to
# track the libraries through package data more than anything...
# help would be appriciated
self.outfiles = self.distribution.data_files
class InstallCMakeLibs(install_lib):
"""
Get the libraries from the parent distribution, use those as the outfiles
Skip building anything; everything is already built, forward libraries to
the installation step
"""
def run(self):
"""
Copy libraries from the bin directory and place them as appropriate
"""
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
self.skip_build = True
bin_dir = self.distribution.bin_dir
# Depending on the files that are generated from your cmake
# build chain, you may need to change the below code, such that
# your files are moved to the appropriate location when the installation
# is run
libs = [os.path.join(bin_dir, _lib) for _lib in
os.listdir(bin_dir) if
os.path.isfile(os.path.join(bin_dir, _lib)) and
os.path.splitext(_lib)[1] in [".dll", ".so"]
and not (_lib.startswith("python") or _lib.startswith(PACKAGE_NAME))]
for lib in libs:
shutil.move(lib, os.path.join(self.build_dir,
os.path.basename(lib)))
# Mark the libs for installation, adding them to
# distribution.data_files seems to ensure that setuptools' record
# writer appends them to installed-files.txt in the package's egg-info
#
# Also tried adding the libraries to the distribution.libraries list,
# but that never seemed to add them to the installed-files.txt in the
# egg-info, and the online recommendation seems to be adding libraries
# into eager_resources in the call to setup(), which I think puts them
# in data_files anyways.
#
# What is the best way?
# These are the additional installation files that should be
# included in the package, but are resultant of the cmake build
# step; depending on the files that are generated from your cmake
# build chain, you may need to modify the below code
self.distribution.data_files = [os.path.join(self.install_dir,
os.path.basename(lib))
for lib in libs]
# Must be forced to run after adding the libs to data_files
self.distribution.run_command("install_data")
super().run()
class InstallCMakeScripts(install_scripts):
"""
Install the scripts in the build dir
"""
def run(self):
"""
Copy the required directory to the build directory and super().run()
"""
self.announce("Moving scripts files", level=3)
# Scripts were already built in a previous step
self.skip_build = True
bin_dir = self.distribution.bin_dir
scripts_dirs = [os.path.join(bin_dir, _dir) for _dir in
os.listdir(bin_dir) if
os.path.isdir(os.path.join(bin_dir, _dir))]
for scripts_dir in scripts_dirs:
shutil.move(scripts_dir,
os.path.join(self.build_dir,
os.path.basename(scripts_dir)))
# Mark the scripts for installation, adding them to
# distribution.scripts seems to ensure that the setuptools' record
# writer appends them to installed-files.txt in the package's egg-info
self.distribution.scripts = scripts_dirs
super().run()
class BuildCMakeExt(build_ext):
"""
Builds using cmake instead of the python setuptools implicit build
"""
def run(self):
"""
Perform build_cmake before doing the 'normal' stuff
"""
for extension in self.extensions:
if extension.name == 'example_extension':
self.build_cmake(extension)
super().run()
def build_cmake(self, extension: Extension):
"""
The steps required to build the extension
"""
self.announce("Preparing the build environment", level=3)
build_dir = pathlib.Path(self.build_temp)
extension_path = pathlib.Path(self.get_ext_fullpath(extension.name))
os.makedirs(build_dir, exist_ok=True)
os.makedirs(extension_path.parent.absolute(), exist_ok=True)
# Now that the necessary directories are created, build
self.announce("Configuring cmake project", level=3)
# Change your cmake arguments below as necessary
# Below is just an example set of arguments for building Blender as a Python module
self.spawn(['cmake', '-H'+SOURCE_DIR, '-B'+self.build_temp,
'-DWITH_PLAYER=OFF', '-DWITH_PYTHON_INSTALL=OFF',
'-DWITH_PYTHON_MODULE=ON',
f"-DCMAKE_GENERATOR_PLATFORM=x"
f"{'86' if BITS == 32 else '64'}"])
self.announce("Building binaries", level=3)
self.spawn(["cmake", "--build", self.build_temp, "--target", "INSTALL",
"--config", "Release"])
# Build finished, now copy the files into the copy directory
# The copy directory is the parent directory of the extension (.pyd)
self.announce("Moving built python module", level=3)
bin_dir = os.path.join(build_dir, 'bin', 'Release')
self.distribution.bin_dir = bin_dir
pyd_path = [os.path.join(bin_dir, _pyd) for _pyd in
os.listdir(bin_dir) if
os.path.isfile(os.path.join(bin_dir, _pyd)) and
os.path.splitext(_pyd)[0].startswith(PACKAGE_NAME) and
os.path.splitext(_pyd)[1] in [".pyd", ".so"]][0]
shutil.move(pyd_path, extension_path)
# After build_ext is run, the following commands will run:
#
# install_lib
# install_scripts
#
# These commands are subclassed above to avoid pitfalls that
# setuptools tries to impose when installing these, as it usually
# wants to build those libs and scripts as well or move them to a
# different place. See comments above for additional information
setup(name='my_package',
version='1.0.0a0',
packages=find_packages(),
ext_modules=[CMakeExtension(name="example_extension")],
description='An example cmake extension module',
long_description=open("./README.md", 'r').read(),
long_description_content_type="text/markdown",
keywords="test, cmake, extension",
classifiers=["Intended Audience :: Developers",
"License :: OSI Approved :: "
"GNU Lesser General Public License v3 (LGPLv3)",
"Natural Language :: English",
"Programming Language :: C",
"Programming Language :: C++",
"Programming Language :: Python",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython"],
license='GPL-3.0',
cmdclass={
'build_ext': BuildCMakeExt,
'install_data': InstallCMakeLibsData,
'install_lib': InstallCMakeLibs,
'install_scripts': InstallCMakeScripts
}
)
Run Code Online (Sandbox Code Playgroud)
一旦用setup.py这种方式编写,构建python模块就像运行一样简单py setup.py,它将运行构建并生成outfiles.
建议您为慢速互联网上的用户或不希望从源构建的用户生成轮子.为此,您需要安装wheelpackage(py -m pip install wheel)并通过执行生成wheel分布py setup.py bdist_wheel,然后twine像使用任何其他包一样上传它.