Create standalone executables from Python scripts
—
Build commands provide setuptools-compatible integration for creating executables and managing the freezing process. The primary command is build_exe, which handles module discovery, dependency resolution, and executable creation with extensive configuration options.
The core build command that creates executables from Python scripts by analyzing dependencies, collecting required modules, and assembling the final distribution.
class build_exe(Command):
"""Build executables from Python scripts."""
description = "build executables from Python scripts"
def initialize_options(self) -> None:
"""Initialize all command options to default values."""
def finalize_options(self) -> None:
"""Validate and finalize option values before execution."""
def run(self) -> None:
"""Execute the build process using Freezer."""
def add_to_path(self, name: str) -> None:
"""Add source directory to sys.path for module discovery."""
def build_extension(
self,
name: str,
module_name: str | None = None
) -> None:
"""Build C extensions during the freezing process."""
def set_source_location(self, name: str, *path_parts: str) -> None:
"""Set source locations from environment variables."""
def has_executables(self) -> bool:
"""Check if distribution has executables defined."""Comprehensive options for controlling the build process, module inclusion/exclusion, optimization, and output formatting.
# Key build options (user_options)
build_exe: str # Build directory for executables
includes: list[str] # Modules to explicitly include
excludes: list[str] # Modules to explicitly exclude
packages: list[str] # Packages to include with all submodules
replace_paths: list[str] # Path replacement mappings
optimize: int # Bytecode optimization level (0, 1, 2)
compress: bool # Compress Python bytecode in zip
zip_includes: list[str] # Files to include in zip archive
zip_include_packages: list[str] # Packages to store in zip
include_files: list[str] # Additional files to copy to build directory
include_msvcr: bool # Include Microsoft Visual C++ runtime (Windows)
bin_includes: list[str] # Binary files to include in build
bin_excludes: list[str] # Binary files to exclude from build
bin_path_includes: list[str] # Binary search paths
bin_path_excludes: list[str] # Binary search paths to excludeOptions for fine-tuning the build process, handling edge cases, and integrating with development workflows.
# Advanced configuration options
no_compress: bool # Disable compression
include_msvcr_version: str # Specific MSVCR version to include
zip_exclude_packages: list[str] # Packages to exclude from zip
constants_modules: list[str] # Constants module definitions
zip_filename: str # Custom zip filename
metadata: dict # Custom metadata for frozen app
path: list[str] # Module search paths
build_lib: str # Library build directory
silent: bool # Suppress build output
init_script: str # Default initialization script# Basic setup.py with build_exe
from cx_Freeze import setup, Executable
setup(
name="MyApp",
version="1.0",
executables=[Executable("main.py")],
options={
"build_exe": {
"build_exe": "dist",
"includes": ["tkinter", "sqlite3"],
"excludes": ["unittest", "test"],
"packages": ["requests", "numpy"],
"include_files": [
("data/", "data/"),
"config.ini"
],
"optimize": 2,
"compress": True
}
}
)
# Command-line usage
# python setup.py build_exe
# python setup.py build_exe --build-exe=custom_dist --includes=pandasControl over module discovery, path replacement, and binary inclusion for complex applications with specific requirements.
# Path replacement format
replace_paths = [
"original_path=replacement_path",
"/usr/local/lib=/app/lib"
]
# File inclusion formats
include_files = [
"source_file", # Copy to build root
("source_file", "dest_file"), # Copy with rename
("source_dir/", "dest_dir/"), # Copy directory
]
# Binary handling
bin_includes = ["libspecial.so", "custom.dll"]
bin_excludes = ["libc.so*", "kernel32.dll"]
bin_path_includes = ["/opt/custom/lib"]
bin_path_excludes = ["/usr/lib/python*/lib-dynload"]The build_exe command follows a structured process that can be customized at various stages.
# Internal build process methods
def _get_executables(self) -> list[Executable]:
"""Get list of executables to build."""
def _create_constants_module(self) -> ConstantsModule:
"""Create constants module for frozen application."""
def _get_freezer_options(self) -> dict:
"""Prepare options for Freezer initialization."""
# Integration points
def get_sub_commands(self) -> list[str]:
"""Get list of sub-commands to run."""
def get_source_files(self) -> list[str]:
"""Get list of source files being processed."""Build options and behavior adapt to the target platform with automatic handling of platform-specific requirements.
Windows:
macOS:
Linux:
# Build-time validation
class OptionError(Exception):
"""Raised for invalid build configuration."""
class SetupError(Exception):
"""Raised for setup script configuration errors."""
# Common validation scenarios:
# - Invalid build directory permissions
# - Missing required modules or packages
# - Conflicting include/exclude specifications
# - Platform-specific option validation
# - Executable script file validationBuild commands integrate with installation commands for complete deployment workflows.
# Related installation commands
class install(Install):
"""Extended install command with executable support."""
class install_exe(Command):
"""Install executables built by build_exe."""
def get_inputs(self) -> list[str]:
"""Get list of files to install."""
def get_outputs(self) -> list[str]:
"""Get list of installed files."""Install with Tessl CLI
npx tessl i tessl/pypi-cx-freeze