Search code examples
pythonpython-2.7cythondistutils

Compile cython code with "python compile.py" and no "build" command-line parameter


I have a compile.py script:

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("module1.pyx"))

that compiles my Cython code. The drawback is that I have to call it with a command-line parameter build:

python compile.py build

Instead, I would like to be able to call this compile.py directly from Sublime Text, as usual, with CTRL+B. To do that, it should work from:

python compile.py

Question: how to modify the above script so that it can be run with python compile.py?


Solution

    • Method #1:

      Use script_args like this:

      setup(ext_modules=cythonize("module1.pyx", build_dir="build"), script_args=['build'])
      

      or

      setup(ext_modules=cythonize("module1.pyx", build_dir="build"), script_args=['build_ext'])
      

      (both work).

      If you want the output files to be in the same directory, you can use:

      setup(ext_modules=cythonize("module1.pyx", build_dir="build"), script_args=['build'], 
                                                  options={'build':{'build_lib':'.'}})
      

      or

      setup(ext_modules=cythonize("module1.pyx", build_dir="build"), script_args=['build_ext'],
                                                  options={'build_ext':{'inplace':True}})
      
    • Method #2:

      Add this on top:

       import sys; sys.argv = ["", "build"]
      

      It's a bit hack-ish but it works fine, and avoids to have to create a new build-system, like with Build and run with arguments in Sublime Text 2 (link kindly provided by @Melvin).