Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython module doesn't work

Tags:

python

cython

I'm trying to produce a simple fibonacci algorithm with Cython. I have fib.pyx:

def fib(int n):
    cdef int i
    cdef double a=0.0, b=1.0
    for i in range(n):
        a, b = a + b, a
    return a

and setup.py in the same folder:

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

setup(ext_modules=cythonize('fib.pyx'))

Then I open cmd and cd my way to this folder and build the code with (I have [http://www.microsoft.com/en-us/download/details.aspx?id=44266](this compiler) :

python setup.py build

Which produces this result:

C:\Users\MyUserName\Documents\Python Scripts\Cython>python setup.py build
Compiling fib.pyx because it changed.
Cythonizing fib.pyx
running build
running build_ext
building 'fib' extension
creating build
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Anaconda\Scripts\gcc.bat -DMS_WIN64 -mdll -O -Wall -IC:\Anaconda\include -IC:
\Anaconda\PC -c fib.c -o build\temp.win-amd64-2.7\Release\fib.o
writing build\temp.win-amd64-2.7\Release\fib.def
creating build\lib.win-amd64-2.7
C:\Anaconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Relea
se\fib.o build\temp.win-amd64-2.7\Release\fib.def -LC:\Anaconda\libs -LC:\Anacon
da\PCbuild\amd64 -lpython27 -lmsvcr90 -o build\lib.win-amd64-2.7\fib.pyd

So it seems the compiling worked and I should be able to import this module with

import fib
ImportError: No module named fib

Where did I go wrong? Edit:

os.getcwd()
Out[6]: 'C:\\Users\\MyUserName\\Documents\\Python Scripts\\Cython\\build\\temp.win-amd64-2.7\\Release'

In [7]: import fib
Traceback (most recent call last):

  File "<ipython-input-7-6c0ab2f0a4e0>", line 1, in <module>
    import fib

ImportError: No module named fib
like image 581
ELEC Avatar asked Mar 23 '15 08:03

ELEC


People also ask

How do you use Cython in Python?

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).


2 Answers

The compiling worked however the library was placed under: build\lib.win-amd64-2.7 so you have to either copy/move the file in the current directory or change your current directory to that one.

You can see this in the last part of the command run:

-o build\lib.win-amd64-2.7\fib.pyd

The -o option stands for output and specifies where it should put the final compiled file.

like image 65
Bakuriu Avatar answered Oct 16 '22 09:10

Bakuriu


Use python setup.py build_ext --inplace

--inplace flag will put your pyd in the working directory

like image 6
Dennis Sakva Avatar answered Oct 16 '22 09:10

Dennis Sakva