Shiv: Python Zipapp Builder

1.0.8 · active · verified Thu Apr 16

Shiv is a command-line utility for building fully self-contained Python zipapps (.pyz files) in compliance with PEP 441. It packages a Python application, its dependencies, and a Python interpreter bootstrap into a single executable file. The current version is 1.0.8, with a release cadence of relatively frequent minor releases.

Common errors

Warnings

Install

Quickstart

This quickstart demonstrates how to create a simple Python script, package it into a self-contained zipapp using `shiv`, and then execute the resulting zipapp.

import subprocess
import sys
import os

# 1. Create a simple Python script to be packaged
script_content = """
# hello_app.py
import sys
def main():
    print(f"Hello from shiv zipapp! Python version: {sys.version.split()[0]}")

if __name__ == '__main__':
    main()
"""
with open("hello_app.py", "w") as f:
    f.write(script_content)

# 2. Build the zipapp using shiv (assuming shiv is installed)
print("Building hello_app.pyz...")
try:
    subprocess.run(
        [sys.executable, "-m", "shiv", "-o", "hello_app.pyz", "-e", "hello_app:main", "."],
        check=True,
        capture_output=True,
        text=True
    )
    print("Zipapp built successfully.")
except subprocess.CalledProcessError as e:
    print(f"Error building zipapp: {e.stderr}")
    sys.exit(1)

# 3. Execute the built zipapp
print("Executing hello_app.pyz...")
try:
    result = subprocess.run(
        [sys.executable, "hello_app.pyz"],
        check=True,
        capture_output=True,
        text=True
    )
    print("Zipapp output:")
    print(result.stdout.strip())
except subprocess.CalledProcessError as e:
    print(f"Error executing zipapp: {e.stderr}")
    sys.exit(1)
finally:
    # 4. Clean up generated files
    if os.path.exists("hello_app.py"):
        os.remove("hello_app.py")
    if os.path.exists("hello_app.pyz"):
        os.remove("hello_app.pyz")
    print("Cleanup complete.")

view raw JSON →