Setup of PyCharm for Cython

前端 未结 1 1071
旧巷少年郎
旧巷少年郎 2020-12-25 08:44

I see that PyCharm supports Cython.

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: \"Co

相关标签:
1条回答
  • 2020-12-25 09:19

    Answering my own question here:

    Let's say we have the function 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. Use a setup file. Make the file 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)
      )
      

      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.

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

      import fib
      fib.fib(2000)
      
    2. 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)
      

      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)
      
    0 讨论(0)
提交回复
热议问题