Skip to content

Instantly share code, notes, and snippets.

@ljaraque
Created June 25, 2018 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ljaraque/66bf3875d39d9b57abdfaa90529c5a0c to your computer and use it in GitHub Desktop.
Save ljaraque/66bf3875d39d9b57abdfaa90529c5a0c to your computer and use it in GitHub Desktop.
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 script.py

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.
Reference: http://bits.citrusbyte.com/protecting-a-python-codebase/

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 script.py :

cython library.py -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 library.so cython.c

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

import main.so
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment