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: "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.
Thanks
Thankfully, Python supports compiled C-extensions through Cython. PyCharm ships with C versions of debugger code, which you can compile to make debugging in PyCharm faster. If you have a large code base, using this speedup extension is reasonable.
To make your Python into Cython, first you need to create a file with the . pyx extension rather than the . py extension. Inside this file, you can start by writing regular Python code (note that there are some limitations in the Python code accepted by Cython, as clarified in the Cython docs).
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
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With