Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify cython output file

Tags:

c++

python

cython

It seems that by default setup from distutils.core with cmdclass set to build_ext, compiles a cpp or c file in the current working directory. Is there a way to determine where the generated c code is written to? Otherwise, a repository will be littered with generated code.

For example this file setup.py will write a file example.c to the current working directory:

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

setup(
      ext_modules = cythonize("example.pyx"))
like image 379
Michael WS Avatar asked Dec 17 '15 21:12

Michael WS


People also ask

Does Cython need to be compiled?

Cython source file names consist of the name of the module followed by a . pyx extension, for example a module called primes would have a source file named primes. pyx . Cython code, unlike Python, must be compiled.


Video Answer


3 Answers

You can pass the option build_dir="directory name" to Cythonize

# rest of file as before
setup(
      ext_modules = cythonize("example.pyx",
                              build_dir="build"))

The above code will put the generated c files in the directory "build" (which makes sense, since by default it's where distutils puts temporary object files and so forth when it's building).


My original answer had working, not build_dir. Thanks to @ArthurTacca for pointing out that that no longer seems to be right.

like image 188
DavidW Avatar answered Oct 06 '22 09:10

DavidW


After initializing an Extension, the parameters can be set to create c in temp directory.

module  = Extension("temp", "temp.pyx")
module.cython_c_in_temp = True 
like image 40
Michael WS Avatar answered Oct 06 '22 08:10

Michael WS


Your setup.py is fine.

To get it to build to a different location, invoke python in the following way:

python setup.py build_ext --build-lib <build directory>

I use the following make rules to automate this:

python_lib_dir=src/lib

cython_output = $(patsubst $(python_lib_dir)/%.pyx,$(python_lib_dir)/%.so, $(shell find $(python_lib_dir) -name '*.pyx'))

$(cython_output):%.so:%.pyx      
    python setup.py build_ext --build-lib $(python_lib_dir)
like image 8
Anders Lindstrom Avatar answered Oct 06 '22 08:10

Anders Lindstrom