Standalone Python executables

Mar 2, 2024    #python  

This post explains how to create standalone executables from Python scripts using cx_Freeze.

Create python env + install cx_Freeze

python -m venv {env}
./{env}/Scripts/activate
python -m pip install --upgrade pip
pip install cx_Freeze

Write build script

The entire build process itself is defined within a build script. Here is an example build file.

import pathlib
import sys
from ctypes.util import find_library


path = pathlib.Path(__file__).absolute().parent

# Metadata
name = "test"
script = path / "src/main.py"

# Build config
optimize = 1
includes = []
excludes = ["tkinter"]
packages = ["OpenGL"]
constants = []
bin_includes = []
bin_excludes = []
platform_libs = {}
include_files = []
zip_include_files = []
zip_include_packages = "*"
zip_exclude_packages = [
    "OpenGL_accelerate",
    "glfw"
] + (["PyQt6"] if sys.platform.startswith("win") else [])
silent_level = 0
include_msvcr = True

# Build system libs
for platform, libs in platform_libs.items():
    if system.platform.startswith(platform):
        for lib in libs:
            if lib_path := find_library(lib):
                bin_includes.append(lib_path)

# Friendly reminder
try:
    import cx_Freeze
except ModuleNotFoundError:
    print("cx_Freeze is not installed!")
    sys.exit(1)


# Build
cx_Freeze.setup(
    name=name,
    executables=[
            cx_Freeze.Executable(
                script=script,
                base="Win32GUI" if sys.platform.startswith("win") else None,
                target_name=name
            )
        ],
    options={
        "build_exe": {
            "optimize": optimize,
            "includes": includes,
            "excludes": excludes,
            "packages": packages,
            "constants": constants,
            "bin_includes": bin_includes,
            "bin_excludes": bin_excludes,
            "include_files": include_files,
            "zip_includes": zip_include_files,
            "zip_include_packages": zip_include_packages,
            "zip_exclude_packages": zip_exclude_packages,
            "silent_level": silent_level,
            "include_msvcr": include_msvcr,
        }
    }
)

Finally build project

Running the build scipt creates a platform-specific standalone executable under the build folder.

./build.py build

Resources