Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Cython';s setup.py?_Python_Python 3.x_Cython - Fatal编程技术网

Python 如何在Cython';s setup.py?

Python 如何在Cython';s setup.py?,python,python-3.x,cython,Python,Python 3.x,Cython,在本教程之后,我正在尝试用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以指定

在本教程之后,我正在尝试用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\u ext--inplace
编译,我如何指定python 3源代码?对于Hello World程序来说,这可能没什么大不了的,但随着我开始在实际项目中使用Cython,这将很重要。

根据,可以通过文件顶部的特殊标题注释使用指令指定Python语言级别,如下所示:

#!python
#cython: language_level=3
似乎没有办法在setup.py中指定这一点。因此,如果您有许多Cython文件,则必须向每个文件添加编译器指令。尽管到目前为止,我遇到的唯一需要此指令的情况是针对您的示例中的print(),并且我已经广泛使用了Cython。

可以传递到
setup.py
-脚本中的
cythonize
-函数:

extensions = cythonize(
               extensions, 
               compiler_directives={'language_level' : "3"})   # or "2" or "3str"
             ) 
另一种可能的语法是

extensions = cythonize(extensions, language_level = "3")

以上内容可能比添加更方便

#cython: language_level=3
对于项目中的每个pyx文件,这可能是必需的,因为自Cython 0.29以来,如果
语言级别

/Main.py:367:FutureWarning:Cython指令“语言级别”不可用 设置,现在使用2(Py2)。这将在以后的版本中更改!文件: XXXXXX.pyx
tree=Parsing.p_模块(s,pxd,full_模块名称)


因为
language\u level
是一个全局设置,所以decorator

cimport cython

@cython.language_level("3")
def do_something():
    pass

甚至不会被cythonized。

如果您使用的是带有扩展名的setup.py,如下所示

然后,您必须添加以下代码段以应用language_level指令(在设置之前(…),谢谢codeman48):


当循环放置在
ext_modules=[…]
内容之后和
设置(…
内容)之前时,此操作有效。谢谢!
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [
    Extension("mymodule1",  ["mymodule1.py"]),
    Extension("mymodule2",  ["mymodule2.py"]),
]

setup(
    name = 'My Program Name',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)
for e in ext_modules:
    e.cython_directives = {'language_level': "3"} #all are Python-3