1 min read

Python Zipapp Module

The zipapp module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API.

Importing the Module

import zipapp

Command Line Usage

You can create an executable archive from a directory containing Python code.

# Create an archive 'myapp.pyz' from the directory 'myapp'
python -m zipapp myapp

You can specify the main function to run using -m.

python -m zipapp myapp -m "myapp:main"

You can also specify the interpreter shebang using -p.

python -m zipapp myapp -p "/usr/bin/env python3"

Programmatic Usage

zipapp.create_archive()

Create an application archive from source, which can be a directory name or a file-like object.

import zipapp

# Create an archive from a directory
zipapp.create_archive('myapp', 'myapp.pyz')

Specifying Main and Interpreter

You can specify the entry point and the interpreter.

import zipapp

zipapp.create_archive(
    'myapp', 
    'myapp.pyz', 
    interpreter='/usr/bin/env python3', 
    main='myapp:main'
)

zipapp.get_interpreter()

Return the interpreter specified in the #! line at the beginning of the archive.

import zipapp

interpreter = zipapp.get_interpreter('myapp.pyz')
print(interpreter)

programming/python/python