我正在按照本教程尝试在 Cython 中编写“Hello World”程序 http://docs.cython.org/src/tutorial/cython_tutorial.html#cython-hello-world
我创建了helloworld.pyx
print("Hello World")
和setup.py
:
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("helloworld.pyx")
)
如何更改 setup.py 以指定我的源是 Python 3,而不是教程中的 Python 2?如果我从命令行调用“cython”命令,它接受 -3
选项。但是,如果我像本教程中所示那样使用 python setup.py build_ext --inplace
进行编译,我该如何指定 Python 3 源代码?对于 Hello World 程序来说,这可能并不重要,但当我开始将 Cython 用于实际项目时,它就很重要了。
最佳答案
一个可以通过language_level
as an option到 setup.py
脚本中的 cythonize
函数:
ext_modules = cythonize(
extensions,
compiler_directives={'language_level' : "3"} # or "2" or "3str"
)
另一种可能的语法是
ext_modules = cythonize(extensions, language_level = "3")
上面的可能比添加更方便
#cython: language_level=3
到项目中的每个 pyx 文件,这可能是必要的,因为自 Cython 0.29 以来有一个警告,如果 language_level
isn't set explicitly :
/Main.py:367: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: XXXXXX.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
因为language_level
是一个全局设置,装饰器
cimport cython
@cython.language_level("3")
def do_something():
pass
甚至不会被 cythonized。
关于python - 如何在 Cython 的 setup.py 中指定 Python 3 源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603628/