Gangmax Blog

Python Zip Application

From here and here.

With “zipapp“, you can create a executable Python archive with all its dependencies.

Basic Usage

Here is an example. Use the following Python file as the target script.

inside.py
1
2
3
4
5
6
7
8
9
10
from termcolor import cprint

def hello_inside():
cprint('Hello from zipapp inside...', 'red')

def main():
hello_inside()

if __name__ == '__main__':
main()

Run the following commands to create the “pyz” package file with “inside.py”.

1
2
3
4
5
mkdir build
mkdir dist
cp inside.py build/
pip install termcolor --target build
python -m zipapp build --main inside:main --output dist/test.pyz

After the “test.pyz” file is generated, you can run “python dist/test.pyz” to execute the Python package.

Advanced Usage

In some case, your code inside a “pyz” file needs to call external Python code out of the “pyz” file. Here is an example.

inside.py
1
2
3
4
5
6
7
8
9
10
11
12
from termcolor import cprint
from outside import hello_outside

def hello_inside():
cprint('Hello from zipapp inside...', 'red')

def main():
hello_inside()
hello_outside()

if __name__ == '__main__':
main()
outside.py
1
2
3
4
from termcolor import cprint

def hello_outside():
cprint('Hello from outside...', 'blue')

Run the following commands to create the “pyz” package file with “inside.py” only.

1
2
3
4
5
mkdir build
mkdir dist
cp inside.py build/
pip install termcolor --target build
python -m zipapp build --main inside:main --output dist/test.pyz

Run the following command to execute the “test.pyz” file.

1
2
3
4
# "/Users/auser/test/dist" is where the "outside.py" resides.
# The "PYTHONPATH" environment variable sets the system path
# where Python looks for dependencies not in the "pyz" file.
PYTHONPATH=/Users/auser/test/dist python dist/test.pyz

Comments