I use anaconda in pycharm, and as you may know, cython has been installed by default in anaconda. My project contains a little cython code, which I want to run in pycharm. How can I do this?
2 Answers
Simpliest way to do this is to use pyximport:
in your main.py add this:
import pyximport
pyximport.install(setup_args={'include_dirs': np.get_include()})
import cython_helper
And place your cython code in cython_helper.pyx file.
If you ran this on windows, before runing your python code you should set ENV variable(VS 2013):
SET VS90COMNTOOLS=%VS120COMNTOOLS%

- 641
- 1
- 7
- 17
The question could mean two different things:
You have a .pyx source file, but you treat it just like any old Python script, and you'd simply like to invoke the actions of the script.
Your .pyx file is an extension module, and after it is built, you want to import from it.
You can use pyximport
for this as in the other answer, but another handy tool is the recent runcython
project. When runcython
is installed, then for case #1 above, you can simply do:
runcython my_file.pyx
from your command prompt, and my_file.pyx
will be compiled, then executed in the same manner that any generic Python script would be. Any top-level statements will be executed, but one extra convention is added for convenience: If there happens to be a function in your script named main
, then runcython
will automatically call it, treating it like the if __name__ == '__main__'
section of a generic Python script. Thus, it is good practice that if you want to do "scripting" with Cython, you should make all your top level definitions, but then put all of "the work" into a top-level function called main
that is defined last.
Note that the usual if __name__ == '__main__'
trick won't work with extension modules in general, because under the hood it relies on the python -m
module execution process, which uses the standard library runpy
and runpy
requires there to be a code object from the executed module -- something that extension modules generally do not have. You'll get a "no code object" error (for example, after building and installing your .so from Cython, like my_file.so
, just try it with python -m my_file
).
For case #2, the runcython
project also provides makecython
which is a huge simplification to the multi-file, distutils-based approach that is relied on more generally. So once you've used runcython
to play around with the code, you can use makecython
for the legitimate build and deployment part.
This is still a new library, so I'm not recommending it if you're talking about a real-world, production dependency or something. For that case, pyximport
is still going to be better.
But for quick and dirty work where you just want to invoke a .pyx
extension module as if it was a generic module, runcython
is a convenient choice.

- 74,674
- 34
- 147
- 228