QNA > H > How To Compile A Python File

How to compile a Python file

  1. Install Cython. Installation is as easy as typing pip install cython or pip3 install cython (for Python 3)
  2. Add the following script to your project folder (as compile.py). It will act as a “makefile” for the build:
  1. from distutils.core import setup 
  2. from distutils.extension import Extension 
  3. from Cython.Distutils import build_ext 
  4.  
  5. ext_modules = [ 
  6. Extension("mymodule1", ["mymodule1.py"]), 
  7. Extension("mymodule2", ["mymodule2.py"]), 
  8. # ... all your modules that need be compiled ... 
  9.  
  10. setup( 
  11. name = 'My Program Name', 
  12. cmdclass = {'build_ext': build_ext}, 
  13. ext_modules = ext_modules 

The script should explicitly enumerate files that you want to be compiled. You can also leave some files uncompiled as well, if you want. Those will still remain importable from binary modules.

3. Add main.py

Make the entry point Python file for your application. You will import and launch all the compiled logic from there. An entry point file is required because Cython does not generate executable binaries by default (though it is capable to), so you will need a dummy Python file, where you simply import all the compiled logic and run it. It can be as simple as:

  1. from logic import main # this comes from a compiled binary 
  2. main () 

4. Run compile.py

Depending on the Python version you use, run:

  1. python compile.py build_ext --inplace 

…or, for Python 3:

  1. python3 compile.py build_ext --inplace 

The above command will generate .so and .c files next to your .py source files.

Di Alphonso

Qual è la differenza tra le licenze GPL, AGPL e LGPL? :: How to create a text file in Python
Link utili