PyGuide

Learn Python with practical tutorials and code examples

Code Snippet Intermediate
• Updated Jul 28, 2025

Python Compilation Code Examples and Scripts

Ready-to-use Python code examples demonstrating different compilation methods including bytecode, executable creation, and performance optimization.

Python Compilation Code Examples and Scripts

This collection demonstrates various ways Python can be compiled, from automatic bytecode generation to creating standalone executables.

Bytecode Compilation Examples #

Manual Bytecode Compilation #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Compile Multiple Files #

import py_compile
import os
from pathlib import Path

def compile_directory(source_dir, target_dir=None):
    """Compile all Python files in a directory to bytecode."""
    source_path = Path(source_dir)
    target_path = Path(target_dir) if target_dir else source_path / '__pycache__'
    
    # Create target directory if it doesn't exist
    target_path.mkdir(exist_ok=True)
    
    compiled_files = []
    for py_file in source_path.glob('*.py'):
        try:
            # Compile each Python file
            compiled_file = target_path / f"{py_file.stem}.pyc"
            py_compile.compile(py_file, compiled_file)
            compiled_files.append(compiled_file)
            print(f"Compiled: {py_file} -> {compiled_file}")
        except py_compile.PyCompileError as e:
            print(f"Error compiling {py_file}: {e}")
    
    return compiled_files

# Usage example
# compiled = compile_directory('my_project', 'compiled_bytecode')

Performance Measurement Script #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Executable Creation Scripts #

PyInstaller Automation Script #

#!/usr/bin/env python3
"""
Automated script to compile Python applications to executables using PyInstaller.
"""

import subprocess
import sys
import os
from pathlib import Path

def compile_to_executable(script_path, options=None):
    """
    Compile Python script to executable using PyInstaller.
    
    Args:
        script_path (str): Path to the Python script
        options (dict): PyInstaller options
    """
    if options is None:
        options = {
            'onefile': True,      # Create single executable
            'windowed': False,    # Console application
            'clean': True,        # Clean cache
            'noconfirm': True     # Overwrite without confirmation
        }
    
    # Build PyInstaller command
    cmd = ['pyinstaller']
    
    if options.get('onefile'):
        cmd.append('--onefile')
    if options.get('windowed'):
        cmd.append('--windowed')
    if options.get('clean'):
        cmd.append('--clean')
    if options.get('noconfirm'):
        cmd.append('--noconfirm')
    
    # Add icon if specified
    if options.get('icon'):
        cmd.extend(['--icon', options['icon']])
    
    # Add the script path
    cmd.append(script_path)
    
    try:
        print(f"Compiling {script_path} to executable...")
        print(f"Command: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ Compilation successful!")
            dist_path = Path('dist') / Path(script_path).stem
            if dist_path.exists():
                print(f"Executable created: {dist_path}")
            return True
        else:
            print("❌ Compilation failed!")
            print("Error:", result.stderr)
            return False
            
    except FileNotFoundError:
        print("❌ PyInstaller not found. Install with: pip install pyinstaller")
        return False

# Example usage
if __name__ == "__main__":
    # Create sample application
    sample_app = """
import sys

def main():
    print("Hello from compiled Python!")
    print(f"Python version: {sys.version}")
    input("Press Enter to exit...")

if __name__ == "__main__":
    main()
"""
    
    # Write sample app
    with open('sample_app.py', 'w') as f:
        f.write(sample_app)
    
    # Compile options
    options = {
        'onefile': True,
        'windowed': False,
        'clean': True,
        'noconfirm': True
    }
    
    # Compile the sample app
    success = compile_to_executable('sample_app.py', options)
    
    if success:
        print("\n🎉 Your Python app has been compiled!")
        print("Check the 'dist' folder for your executable.")

Cross-Platform Compilation Helper #

import platform
import subprocess
import json
from pathlib import Path

class CrossPlatformCompiler:
    """Helper class for cross-platform Python compilation."""
    
    def __init__(self, script_path):
        self.script_path = Path(script_path)
        self.platform = platform.system().lower()
        self.config = self.load_config()
    
    def load_config(self):
        """Load platform-specific compilation configuration."""
        return {
            'windows': {
                'extension': '.exe',
                'icon_format': '.ico',
                'extra_options': ['--windowed']  # for GUI apps
            },
            'darwin': {  # macOS
                'extension': '.app',
                'icon_format': '.icns',
                'extra_options': ['--windowed', '--osx-bundle-identifier', 'com.example.app']
            },
            'linux': {
                'extension': '',
                'icon_format': '.png',
                'extra_options': []
            }
        }
    
    def compile_for_platform(self, target_platform=None):
        """Compile for specific platform or current platform."""
        platform_key = target_platform or self.platform
        
        if platform_key not in self.config:
            raise ValueError(f"Unsupported platform: {platform_key}")
        
        config = self.config[platform_key]
        
        # Build command
        cmd = [
            'pyinstaller',
            '--onefile',
            '--clean',
            '--noconfirm',
            f'--name={self.script_path.stem}{config["extension"]}',
        ]
        
        # Add platform-specific options
        cmd.extend(config['extra_options'])
        cmd.append(str(self.script_path))
        
        print(f"Compiling for {platform_key}...")
        print(f"Command: {' '.join(cmd)}")
        
        try:
            result = subprocess.run(cmd, check=True, capture_output=True, text=True)
            print(f"✅ Successfully compiled for {platform_key}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ Compilation failed for {platform_key}")
            print(f"Error: {e.stderr}")
            return False

# Usage example
# compiler = CrossPlatformCompiler('my_app.py')
# compiler.compile_for_platform('windows')

Summary #

These code examples demonstrate that Python can indeed be compiled in multiple ways:

  • Bytecode compilation happens automatically and can be controlled manually
  • Executable creation is possible with PyInstaller and similar tools
  • Performance measurement helps evaluate compilation benefits
  • Cross-platform compilation ensures your apps work everywhere

Use these snippets as starting points for your own Python compilation workflows.

Related Snippets

Snippet Intermediate

Python Enumerate Zip: Ready-to-Use Code Examples

Copy-paste Python enumerate zip code snippets for combining multiple sequences with index tracking and parallel iteration.

#python #enumerate #zip +2
View Code
Syntax
Snippet Intermediate

Python Error Frame Inspection Code Examples

Ready-to-use Python code snippets for inspecting error frames, analyzing stack traces, and debugging frame-related issues effectively.

#python #error #frame +2
View Code
Syntax
Snippet Intermediate

Python Error Handling Code Snippets: Try-Except Examples

Ready-to-use Python error handling code snippets. Copy-paste examples for common error handling patterns and exception management.

#python #error #exception +2
View Code
Syntax
Snippet Intermediate

Python Script Scheduling Fixes - Code Examples

Ready-to-use Python code snippets to fix scripts that work in terminal but fail when scheduled via cron or automation tools.

#python #automation #cron +2
View Code
Syntax