用Cython进行setup_requires吗?
我正在setup.py
使用一些Cython扩展模块为项目创建文件。
我已经使这个工作了:
from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
ext_modules=cythonize([ ... ]),
)
这安装很好。但是,这假定安装了Cython。如果未安装怎么办?我了解这是该setup_requires
参数的用途:
from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
setup_requires=['Cython'],
...,
ext_modules=cythonize([ ... ]),
)
但是,如果尚未安装Cython,则当然会失败:
$ python setup.py install
Traceback (most recent call last):
File "setup.py", line 2, in <module>
from Cython.Build import cythonize
ImportError: No module named Cython.Build
正确的方法是什么?我Cython
只setup_requires
需要Cython
在步骤运行后以某种方式导入,但是我需要为了指定ext_modules
值。
-
您必须包裹
from Cython.Build import cythonize
在一个try- except
,而在except
,定义cythonize
为虚函数。这样,可以在不失败的情况下加载脚本ImportError
。然后,在
setup_requires
处理完参数后,Cython
将进行安装并重新执行安装脚本。由于此时Cython
已安装,因此您可以成功导入cythonize
try: from Cython.Build import cythonize except ImportError: def cythonize(*args, **kwargs): from Cython.Build import cythonize return cythonize(*args, **kwargs)
编辑
如评论中所述,setuptools处理完缺少的依赖关系后,将不会重新加载Cython。我以前没想过,但是您也可以尝试采用后期绑定方法来解决问题
cythonize