How to compile Python code to native executable

First, you need to create a python application, in this case just a “Hello World” test.py file:

$ cat test.py
print "Hello World"

Convert the Python code in C code using Cython:

$ cython --embed test.py

We need to use “–embed” because we don’t want a shared library, but a real main program.

Compile the generated “test.c” file:

$ gcc test.c -o test `pkg-config --libs --cflags python2`

Test it:

$ ./test 
Hello World

Sources:
http://stackoverflow.com/questions/5105482/compile-main-python-program-using-cython
https://bbs.archlinux.org/viewtopic.php?id=180538
http://www.behnel.de/cython200910/talk.html

2 thoughts on “How to compile Python code to native executable

  1. Is it possible to statically compile libpython2.7.so into the executable so it executes on systems without Python installed?

    1. Hi Carsten,
      I don’t know. I think it is possible, you will get a libpython.a and it could be linked with your app to create a statically linked executable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s