【发布时间】:2017-10-17 07:41:31
【问题描述】:
我有一个问题。我想分发我的 cython 驱动的包,但我看不到在 setup.py 中构建它们的简单方法。我希望 setup.py :
- 最重要的是:在没有 cython 的情况下安装我的包(从预生成的 C 文件或预先安装 cython)
- 在 sdist 上重建(运行 cythonize)包
- 不需要对我的 cython 模块列表进行硬编码(只需使用 glob 或其他东西)
- 能够在没有 .c 文件(不应存储在 git 中)或 .pyx(可能不分发)的情况下工作。当然,其中至少有一套会一直存在。
目前在我的痒包中,我正在使用这个相当复杂的代码:
import os
from glob import glob
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.sdist import sdist as _sdist
from distutils.core import setup
from distutils.core import Extension
def generate_extensions():
return [
# Compile cython-generated .c files into importable .so libraries.
Extension(os.path.splitext(name)[0], [name])
for name in C_FILES
]
# In distribution version, there are no pyx files, when you clone package from git, there will be no c files.
CYTHON_FILES = glob('itchy/*.pyx')
C_FILES = glob('itchy/*.c')
extensions = generate_extensions()
class build_ext(_build_ext):
def run(self):
# Compile cython files (.pyx, some of the .py) into .c files if Cython is available.
try:
from Cython.Build import cythonize
if CYTHON_FILES:
cythonize(CYTHON_FILES)
# Update C_FILES in case they were originally missing.
global C_FILES, extensions
C_FILES = glob('itchy/*.c')
extensions = generate_extensions()
else:
print('No .pyx files found, building extensions skipped. Pre-built versions will be used.')
except ImportError:
print('Cython is not installed, building extensions skipped. Pre-built versions will be used.')
assert C_FILES, 'C files have to be present in distribution or Cython has to be installed'
_build_ext.run(self)
class sdist(_sdist):
def run(self):
# Make sure the compiled Cython files in the distribution are up-to-date
self.run_command("build_ext")
_sdist.run(self)
setup(
(...)
ext_modules = extensions,
cmdclass = {
'build_ext': build_ext,
'sdist': sdist,
},
)
【问题讨论】: