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

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

问题描述

我看到 PyCharm 支持 Cython.

我总是可以在终端中编译和运行,但我想知道在 PyCharm 中是否有办法做到这一点.在链接中它说:编译是使用外部工具完成的.首选的构建系统(Makefile、setup.py 等)应该配置为外部工具."我想知道如何进行此配置.非常感谢 PyCharm 中使用 Cython 的 Hello World 小示例.

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. 使用安装文件.制作文件 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 文件.要运行此文件,您必须转到 Tools --> Run setup.py Task.然后输入 build_ext 作为 task name,并在提示输入 Command Line 时输入 --inplace.生成文件fib.cfib.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.cfib.ofib.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天全站免登陆