Skip to content

Instantly share code, notes, and snippets.

@bsnux
Created September 10, 2021 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsnux/d8c974aa922c8184388aa9693e984cd7 to your computer and use it in GitHub Desktop.
Save bsnux/d8c974aa922c8184388aa9693e984cd7 to your computer and use it in GitHub Desktop.
Creating Python Standalone Applications with zipapp

Creating Python Standalone Applications with zipapp

zipapp module allows us to create self-contained Python standalone programs that can be distributed to users who have Python already installed on their system.

Python packages not using C extensions can be bundled as well. shiv is recommended for those applications using those kind of extensions. In general, if your dependencies don't require a C compiler, you should be good to go using zipapp module.

Simple aplication listing current directory content

Directory structure for source code:

/tmp/listd ᐅ tree
.
├── listdir
│   ├── __main__.py
│   └── listdir.py
└── requirements.txt

Where listdir/__main__py contains the following lines:

import listdir


listdir.run()

And listdir/listdir.py these lines:

from shell_cmd import sh


def run():
    print(sh("ls -l"))

Finally requirements.txt contains this line:

shell-cmd==1.0.2

Packaging the application

python -m pip install -r requirements.txt --target listdir
rm -rf listdir/*.dist-info
rm -rf listdir/**/__pycache__
python -m zipapp listdir

Executing the standalone

The final listdir.pyz is ready for distribution and you can execute it using the following command:

python listdir.pyz

Using the interpreter

It's possible to specify the interpreter as the command to run. This means you can invoke directly to the standalone:

python -m zipapp -p "/usr/bin/env python" listdir
./listdir.pyz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment