设置Cython的PyCharm [英] Setup of PyCharm for Cython

查看:538
本文介绍了设置Cython的PyCharm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 PyCharm支持Cython

我总是可以在终端中编译和运行,但是我想知道PyCharm是否有办法做到这一点。在链接中显示:编译是使用外部工具完成的。首选的构建系统(Makefile,setup.py等)应配置为外部工具。我想知道如何进行此配置。

I could always compile and run in terminal, but I'm wondering if there is a way to do this in PyCharm. In the link it says: "Compilation is done using external tools. The preferred build systems (Makefile, setup.py, etc.) should be configured as external tools." I'm wondering how to do this configuration. A small Hello World example in PyCharm using Cython would be much appreciated.

谢谢

推荐答案

在这里回答我自己的问题:

Answering my own question here:

假设我们具有函数 fib.pyx

def fib(n):
"""Print the Fibonacci series up to n."""
a, b = 0, 1
while b < n:
    print b,
    a, b = b, a + b

可以使用两种方法来编译和运行

There are two ways to compile and run this


  1. 使用安装文件。从distutils.core文件中创建文件 setup.py

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

ext_options = {"compiler_directives": {"profile": True}, "annotate": True}
setup(
    ext_modules = cythonize("fib.pyx", **ext_options)
)

ext_options 包含在此处以生成带有注释的html文件。要运行此文件,您必须转到工具->运行setup.py Task 。然后输入 build_ext 作为任务名称,并在提示输入命令行时输入-就地。生成文件 fib.c fib.o 和可执行文件 fib.so 。注释文件 fib.html 也已创建。

The ext_options is included here to generate the html file with annotations. To run this file you have to go to Tools --> Run setup.py Task. Then type in build_ext as task name and when prompted for Command Line input type --inplace. The files fib.c, fib.o and the executable file fib.so is generated. The annotation file fib.html is also created.

现在,以下代码应可在任何python文件中使用,例如 main .py

Now, the following code should work in any python file, for example main.py:

import fib
fib.fib(2000)


  • 最简单的方法是使用 pyximport 。不需要安装文件。请注意,仅当您的模块不需要任何额外的C库或特殊的构建设置。 文件 main.py 现在应如下所示:

  • The much easier way to go is to use pyximport. No setup file is needed. Note that this can only be used if "your module doesn’t require any extra C libraries or a special build setup." The file main.py should now look like:

    import pyximport; pyximport.install()
    import fib
    fib.fib(2000)
    

    据我了解,即使 fib.c fib.o fib.so 文件没有执行相同的代码编译,最终出现在项目文件夹中。 fib.html 代码也不会生成,但是可以通过在主文件中添加两行来解决。现在用新行 main.py 来添加:

    As far as I understand the same compilation of code takes place even though the fib.c, fib.o and fib.so files don't end up in the project folder. The fib.html code is not generated either, but this can be fixed by adding two lines to the main file. With the new lines main.py is now:

    import pyximport; pyximport.install()
    import subprocess
    subprocess.call(["cython", "-a", "fib.pyx"])
    import fib
    fib.fib(2000)
    


  • 这篇关于设置Cython的PyCharm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆