PEX Packaging Toolchain
PEX (Python EXecutable) is a powerful Python packaging tool that creates self-contained Python environments, known as PEX files. These files bundle Python code, dependencies, and optionally a Python interpreter into a single executable, making applications portable and ensuring reproducible builds without needing `pip` or virtual environments on the target system. It simplifies deployment by providing a single artifact. The current version is 2.92.1, and it maintains a rapid release cadence with frequent bug fixes and feature enhancements.
Warnings
- gotcha PEX has explicit Python version compatibility requirements (e.g., `!=3.0.*, !=3.1.*, ..., <3.16, >=2.7`). Always verify the `requires_python` specification for the PEX version you are using. Attempting to build or run a PEX with an incompatible Python interpreter can lead to failures.
- gotcha PEX is predominantly a command-line interface tool (`pex ...` or `python -m pex ...`). While a programmatic API (`pex.pex_builder.PEXBuilder`) exists, it is generally intended for complex build system integrations, not typical application-level programmatic use. Most user interactions should be via the CLI.
- gotcha PEX extensively uses a local cache (defaulting to `~/.pex`). Issues with stale or corrupted cache entries can lead to unexpected build failures or using outdated dependencies. Recent versions have addressed specific caching bugs.
- breaking Versions prior to 2.91.8 had a bug where `--pylock` could fail when the lock file specified local project dependencies using relative paths. This could lead to build failures or incorrect dependency resolution.
Install
-
pip install pex
Imports
- PEXBuilder
from pex.pex_builder import PEXBuilder
Quickstart
# Create a simple Python script
echo 'import sys; import requests; print(f"Python: {sys.version.splitlines()[0]}"); print(f"Requests: {requests.__version__}")' > hello_pex.py
# Build a PEX file that includes 'requests' and executes 'hello_pex.py'
# The --python-shebang ensures the PEX uses the system's python3 or specified path
pex requests --python-shebang /usr/bin/env python3 -o hello.pex -m hello_pex
# Execute the PEX file
./hello.pex