python - 如何在 Cython 的 setup.py 中指定 Python 3 源?

标签 python python-3.x cython

我正在按照本教程尝试在 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 optionsetup.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/

相关文章:

python - Boost Python hello 示例给出错误。

python - 将 .ui 文件转换为 .py 文件时出错

Python 替换正则表达式中的第 n 个匹配项

android - 使用 Python 服务器和 Android 客户端进行套接字编程

python - 我可以有一个 main() Click 函数来调用所有其他子命令吗?

python - Cython - 将 C++ 函数返回的 C++( vector 和非 vector )对象公开给 Python

python - 多个按钮 Tkinter - Canvas 上的位置

linux - Python3x的Tesseract-OCR模块安装错误

c++ - 如何将返回 C++ 自定义类的函数与 Cython 连接?

python - Cython int ** 和 int * 类型