[今天快:我正在学习Python的distutils库的内容,我想在我的包中包括一个python扩展模块(.pyd)。我当然知道,推荐的方法是在创建软件包时让distutils编译扩展,但这是一个相当复杂的扩展,它跨越了许多源文件并引用了多个外部库,因此要花很多时间才能获得所有东西工作正常。
同时,我拥有Visual Studio扩展的已知工作版本,并希望在安装程序中使用它作为临时解决方案,使我可以专注于其他问题。但是,我无法将其指定为模块,因为这些显然必须具有显式的.py扩展名。如何在setup.py中指出要包含一个预编译的扩展模块?
((如果有关系,请使用Python 3.1)
我通过重写Extension.build_extension解决了这个问题:
setup_args = { ... }
if platform.system() == 'Windows':
class my_build_ext(build_ext):
def build_extension(self, ext):
''' Copies the already-compiled pyd
'''
import shutil
import os.path
try:
os.makedirs(os.path.dirname(self.get_ext_fullpath(ext.name)))
except WindowsError, e:
if e.winerror != 183: # already exists
raise
shutil.copyfile(os.path.join(this_dir, r'..\..\bin\Python%d%d\my.pyd' % sys.version_info[0:2]), self.get_ext_fullpath(ext.name))
setup_args['cmdclass'] = {'build_ext': my_build_ext }
setup(**setup_args)
尝试使用package_data:http://docs.python.org/distutils/setupscript#installing-package-data
我在使用Python 3.7,CMake 3.15.3和Swig 4.0.1以及Visual Studio 2017构建扩展库时遇到了同样的问题。构建系统生成三个文件:mymodule.py,_mymodule.lib和_mymodule.pyd。经过一堆反复试验后,我发现以下组合有效:
[metadata]
name = mymodule
version = 1.0
[options]
include_package_data = True
package_dir=
=src
packages=mymodule
python_requires '>=3.7'
[options.package_data]
* = *.pyd
setup.py
setup.cfg
src/
mymodule/
__init__.py
_mymodule.pyd
setup()
这需要CMake将'mymodule.py'输出文件重命名为'init。py'。我是通过CMake中的“安装”命令完成此操作的:
install (TARGETS ${SWIG_MODULE_${PROJECT_NAME}_REAL_NAME} DESTINATION "${CMAKE_BINARY_DIR}/dist/src/${PROJECT_NAME}")
install (FILES
setup.py
setup.cfg
DESTINATION "${CMAKE_BINARY_DIR}/dist"
)
install (FILES
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.py
DESTINATION "${CMAKE_BINARY_DIR}/dist/src/${PROJECT_NAME}"
RENAME "__init__.py"
[我相信进行这项工作的关键秘诀是将构建输出重组为Python软件包,而不是尝试使用默认的Build输出作为Python脚本进行安装。