Compiling Python Code

Loading

Python is an interpreted language, meaning its source code is executed line by line instead of being compiled into machine code beforehand. However, Python does provide ways to compile code into bytecode or even convert it into standalone executables.

In this guide, we’ll cover:
How Python executes code (Interpretation vs. Compilation)
Bytecode Compilation (.pyc files)
Ahead-of-Time (AOT) Compilation
Just-in-Time (JIT) Compilation
Compiling Python into Executables (.exe, .app, etc.)


1. Python Execution Process

Python follows a two-step process:
1️⃣ Source Code (.py) → Bytecode (.pyc)
2️⃣ Bytecode → Execution by Python Virtual Machine (PVM)

When you run a Python script:

python script.py
  • Python first compiles the script into bytecode (.pyc files).
  • The Python Virtual Machine (PVM) executes the bytecode.

2. Bytecode Compilation (.pyc Files)

Python automatically compiles scripts into bytecode and stores them in the __pycache__ directory.

How to Compile Python Code to Bytecode

python -m compileall script.py

This generates a compiled bytecode file inside __pycache__/:

__pycache__/script.cpython-39.pyc

Faster execution on subsequent runs
No need to recompile unless code changes

Manually Running a .pyc File

To execute a .pyc file, use:

python script.pyc

3. Ahead-of-Time (AOT) Compilation

Python provides tools to compile scripts into native executables using:

  • Cython (compiles Python to C)
  • Nuitka (compiles Python to C++)
  • PyInstaller (packages Python into standalone executables)

4. Just-in-Time (JIT) Compilation with PyPy

JIT compilers optimize execution by translating code at runtime.
Faster than standard CPython for long-running programs

Install PyPy (Alternative Python Interpreter)

sudo apt install pypy

Run a script using PyPy:

pypy script.py

Improves performance for loops and computations


5. Compiling Python to Executables (.exe, .app, etc.)

If you want to distribute a Python application without requiring Python to be installed, you can convert it into a standalone executable.

Using PyInstaller

Step 1: Install PyInstaller

pip install pyinstaller

Step 2: Compile Python Script into an Executable

pyinstaller --onefile script.py

This generates:

dist/script.exe  (Windows)
dist/script (Linux/macOS)

No need for Python to be installed
Creates a single-file executable


6. Compiling Python to C using Cython

Cython can convert Python code into C code, improving performance.

Step 1: Install Cython

pip install cython

Step 2: Create a Python Script (script.py)

def hello():
print("Hello, World!")

Step 3: Compile to C

cython --embed -o script.c script.py
gcc -o script script.c $(python3-config --cflags --ldflags)

Now, run the compiled binary:

./script

Faster execution
Protects source code

Leave a Reply

Your email address will not be published. Required fields are marked *