用Cython进行setup_requires吗?

发布于 2021-01-29 18:39:01

我正在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

正确的方法是什么?我Cythonsetup_requires需要Cython在步骤运行后以某种方式导入,但是我需要为了指定ext_modules值。

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您必须包裹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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看