Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Compiling Python Code

Compiling Python Code

###1. Compile to .pyo

To compile python code it is necessary to rung the following command over the python script:

python -OO -m py_compile

The result will be a .pyo file which can be renamed to any string or .py file.
If the code will be imported by another script then it must be named to .pyc.

Warning: Be careful with the version of Python. For example python 2.4 compiled might not run on python 2.7.

###2. Compile to C.

We need to use cython compiler. To install it we need to do:

sudo apt-get install cython

Then we can compile our python library :

cython -o cython.c

We hace named cython.c the C compiled file because it is just a transition file that should be discarded after obtaining the .so file.
Then compile with GCC:

 gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o cython.c

Thus, the file to be used for importing in a python script is
Note: If the script compiled is not just a library, but an executable script, it can be executed with a python script containing:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.