17

I am starting to compile my Python 3 project with Cython, and I would like to know if it's possible to reduce my current compile time workflow to a single instruction.

This is my setup.py as of now:

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

extensions = [
    Extension("v", ["version.py"]),
    Extension("*", ["lib/*.py"])
]

setup(
    name = "MyFirst App",
    ext_modules = cythonize(extensions),
)

And this is what I run from shell to obtain my executables:

python3 setup.py build_ext --inplace
cython3 --embed -o main.c main.py
gcc -Os -I /usr/include/python3.5m -o main main.c -lpython3.5m -lpthread -lm -lutil -ldl

This whole process works just fine, I'd like to know if there is a way to also embed the last two instruction in the setup.py script.

Thank you

Guerriky
  • 529
  • 1
  • 5
  • 15
  • Don't think the answer is good enough to justify flagging as a duplicate, but it might be useful https://stackoverflow.com/questions/31307169/how-to-enable-embed-with-cythonize – DavidW Oct 19 '17 at 07:47
  • 1
    Hi @DavidW. I tried that route, and I can get a compilable main .c file. However, the cythonize method still produces a non-standalone main.so file. If I compile the produced main.c it works. I'm dashing through the docs, but I don't know what I'm missing... – Guerriky Oct 20 '17 at 08:22
  • @Guerriky Same issue. – JeffHeaton Jan 30 '19 at 20:51
  • I only know how to do this on windows. but you can put all of your cmd instructions in a .bat file and than just call that file – Julian wandhoven Feb 23 '21 at 21:51
  • 1
    create a bash file with your 3 commands ? – Sylvain May 06 '21 at 16:42
  • You can use the subprocess module (https://docs.python.org/3/library/subprocess.html) to execute shell commands. – Ronald van Elburg Oct 15 '22 at 13:57

1 Answers1

1

Start off with checking out the docs for the utility you're using. If there are complicated arguments, there is probably a config file.

This should tidy up your first command:

# setup.cfg
[build_ext]
inplace=1

I don't see anything in the docs about a post-build step, and I wouldn't really expect this process to execute shell commands afterwards. build_ext is for building python. make is very available and usual for building C binaries.

Add a Makefile to your project. If you have gccinstalled, you likely have make already:

# Makefile (lines need to start with tab)

compile:
    python3 setup.py build_ext --inplace
    cython3 --embed -o main.c main.py
    gcc -Os -I /usr/include/python3.5m -o main main.c -lpython3.5m -lpthread -lm -lutil -ldl

Now you can just type make or make compile to get the desired affect.

trevorgrayson
  • 1,806
  • 1
  • 21
  • 29