python – 使用distutils,其中swig接口文件位于src文件夹中

我有一个看起来像这样的setup.py:

from setuptools import setup, Extension
import glob

sources = glob.glob('src/*.cpp') + glob.glob('src/*.i')
# this is ugly, but otherwise I get the wrapper included twice
sources = [source for source in sources if '_wrap' not in source]
setup(
    name = 'engine',
    ext_modules = [
        Extension(
            '_engine',
            sources = sources,
            swig_opts = ['-c++'],
            include_dirs = ['src']
        )
    ],
    py_modules = ['engine']
    package_dir = {'' : 'src'}
)

现在只要我运行安装两次就行了.第一次,swig在src目录中创建engine.py.但它不会被复制到目标.第二次运行setup.py文件时,发现并安装了engine.py.有没有办法让它第一次全部工作?

最佳答案 我同意这应该开箱即用,并认为它是一个错误.

实现这一目标的一个选择是简单地改变构建事物的顺序.默认情况下,setup.py将首先收集python模块,然后构建任何外部包.

您可以通过对默认构建类进行子类化来更改构建顺序,然后让setup.py通过cmdclass选项使用您的自定义构建类.

from setuptools import setup, Extension
from distutils.command.build import build as _build

#Define custom build order, so that the python interface module
#created by SWIG is staged in build_py.
class build(_build):
    # different order: build_ext *before* build_py
    sub_commands = [('build_ext',     _build.has_ext_modules),
                    ('build_py',      _build.has_pure_modules),
                    ('build_clib',    _build.has_c_libraries),
                    ('build_scripts', _build.has_scripts),
                   ]

 setup(
    name = 'engine',
    cmdclass = {'build': build },  #Use your own build class
    ext_modules = [Extension('_engine',
                             sources = sources,
                             swig_opts = ['-c++'],
                             include_dirs = ['src']
                   )],
    ...
点赞