How to compile a Python file
- Install Cython. Installation is as easy as typing pip install cython or pip3 install cython (for Python 3)
- Add the following script to your project folder (as compile.py). It will act as a “makefile” for the build:
- from distutils.core import setup
- from distutils.extension import Extension
- from Cython.Distutils import build_ext
- ext_modules = [
- Extension("mymodule1", ["mymodule1.py"]),
- Extension("mymodule2", ["mymodule2.py"]),
- # ... all your modules that need be compiled ...
- ]
- setup(
- name = 'My Program Name',
- cmdclass = {'build_ext': build_ext},
- 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:
- from logic import main # this comes from a compiled binary
- main ()
4. Run compile.py
Depending on the Python version you use, run:
- python compile.py build_ext --inplace
…or, for Python 3:
- python3 compile.py build_ext --inplace
The above command will generate .so and .c files next to your .py source files.
Articoli simili
- How to compile and execute C programs (not C++) from Sublime Text 3
- How to compile and run github projects
- Come spostare i file del sistema operativo Windows 10 su un'altra unità (file di programma e file di programma x86 in particolare)
- È consigliabile imparare Tkinter in Python per avanzare la propria carriera o per ottenere una migliore offerta di lavoro come sviluppatore Python?