简体   繁体   English

在解释器中运行Cython代码

[英]Running Cython code within the interpreter

I'm a Matlab and C++ user, and have recently discovered python (spyder) as a possible replacement for both. 我是Matlab和C ++用户,最近发现python(spyder)可能替代它们。 One of the main benefits I thought python had was the ability to work in interpreter mode, and then seamlessly translate it into fast compiled code once I'm satisfied with the result. 我认为python的主要好处之一是能够在解释器模式下工作,然后在我对结果满意后将其无缝转换为快速编译的代码。 The interpreted environment is great for prototyping, analyzing data while stopped at a breakpoint, throwing plots and images all around, etc. 解释的环境非常适合原型设计,在断点处停止分析数据,在周围投掷图形和图像等。

I started looking into Cython, and I don't fully understand the programming flow. 我开始研究Cython,但我并不完全理解编程流程。 Lets say you have a .py code you'd like to speed up - Do you have to write a .pyx file from scratch? 假设你有一个你想要加速的.py代码 - 你是否必须从头开始编写.pyx文件? Can you run a .pyx file in interpreted mode as if it were a regular .py file (before compiling)? 你可以在解释模式下运行.pyx文件,就好像它是一个普通的.py文件(在编译之前)吗? How do you debug the code in a .pyx file? 如何调试.pyx文件中的代码?

I don't have too much experience with Cython, but judging from this entry in their documentation, the recommended workflow is to have a setup.py file with the following lines: 我没有太多Cython的经验,但从他们的文档中的这个条目判断,推荐的工作流程是有一个setup.py文件,其中包含以下行:

from distutils.core import setup
from Cython.Build import cythonize

setup(name='Hello world app', ext_modules=cythonize("hello.pyx"))

Here hello.pyx is just an example file, you will have to replace the string to reference your Python script. 这里hello.pyx只是一个示例文件,您必须替换该字符串以引用您的Python脚本。

Afterwards you will be able to call 之后你就可以打电话了

python setup.py build_ext --inplace

which will compile your code and leave you with a new file. 这将编译您的代码并留下一个新文件。 Now, as long as that file is in the same directory, you can easily import what you defined in your file, just like with any other module. 现在,只要该文件位于同一目录中,您就可以轻松导入您在文件中定义的内容,就像使用任何其他模块一样。 Eg, suppose you compiled a file hello.pyx with the function f , you could write: 例如,假设您使用函数f编译了一个文件hello.pyx ,您可以编写:

from hello import f

and then proceed to use f . 然后继续使用f


Now, regarding your other questions. 现在,关于你的其他问题。 .pyx seems to just indicate, that this should be Cython code, there is no real difference. .pyx似乎只是表示,这应该是Cython代码,没有真正的区别。 Using the method with a setup.py script as described above, you could also reference a file with the ending .py . 如上所述,使用带有setup.py脚本的方法,您还可以引用末尾为.py的文件。 However, Python won't allow you to import from .pyx files, only from the files created after compiling. 但是,Python不允许您从.pyx文件导入,只能从编译后创建的文件导入。

As to how you would debug code in a .pyx file, I don't have enough information on that, though you could probably just debug the non-compiled file like a .py file. 至于如何调试.pyx文件中的代码,我没有足够的信息,尽管你可能只是调试非编译文件,如.py文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM