[tutorial] PEX Unpacked: Building and Executing Python Executables with Ease

What is “PEX”?

The full name of PEX is Python Executable. This is an open-source tool for building a virtual environment to execute your Python code. However, be cautious when using PEX because it does not include a Python interpreter; thus, your computer must have a Python environment installed.

The process of executing .pex

When you run a .pex file, the system reads the shebang line at the top of the file, #!/usr/bin/env python, to invoke the Python interpreter to execute the script.

Practice

Install PEX

1
pip install pex

Enter Interpretable pex environemt

Easy way

1
2
3
4
5
6
7
8
9
10
11
12
# Enter an interpretable Pex environment without specifying a Python version
pex

# Enter an interpretable Pex environment specifying a specific Python version
pex --python=python3.12 # specific python version

---
Pex 2.16.1 ephemeral hermetic environment with no dependencies.
Exit the repl (type quit()) and run `pex -h` for Pex CLI help.
Python 3.11.4 (main, Jul 5 2023, 08:40:20) [Clang 14.0.6 ] on darwin
Type "help", "pex", "copyright", "credits" or "license" for more information.
>>>

Advanced

1
2
3
4
5
6
7
8
# Specifying requirements
pex pandas

---
Pex 2.16.1 ephemeral hermetic environment with 1 requirement and 6 activated distributions.
Python 3.11.4 (main, Jul 5 2023, 08:40:20) [Clang 14.0.6 ] on darwin
Type "help", "pex", "copyright", "credits" or "license" for more information.
>>> import pandas as pd

Package .py into pex file

1
2
3
4
5
6
7
8
9
# demo.py

import pandas as pd

def main():
print(f"Hello, World! The pandas version is {pd.__version__}")

if __name__ == "__main__":
main()
1
pex -D . -e demo:main -o demo.pex -r requirements.txt
1
2
3
4
# Execute PEX script
./demo.pex

>>> Hello, World! The pandas version is 2.2.2
  • -D: Source directory
  • -e: Entry point for the PEX application
  • -o: Output file name for the PEX file
  • -r: Specifies requirements file that lists the dependencies

Reference

[tutorial] PEX Unpacked: Building and Executing Python Executables with Ease

https://hsiangjenli.github.io/blog/tutorial_pex_unpacked/

Author

Hsiang-Jen Li

Posted on

2024-08-15

Updated on

2024-12-18

Licensed under