Package: zipapps
zipappsChangelogszipappsis apure-pythonlibrary, to package your python code into a single zip file with its dependencies.Depends onPEP441+zipapp+zipimport.What is the.pyz?.pyztoPythonis like.jartoJava.They are both zip archive files which aggregate many packages and associated metadata and resources (text, images, etc.) into one file for distribution.All you need is thePython Interpreteras the runtime environment.So, what couldzipappsbe?packaging toolcompress your package folder into a zip file.single-file virtual environmenta portable site-packages.dependences installerlazy install requirements while first running.set of import-pathadd manyvenv.pyzfiles to PYTHONPATH automatically.requirements.txt freezing toolkitusevenvto freeze your pip packages.PS: The pyz extension can be modified to any character you want, such as.pyand.zip.Install & Quick Startpip install zipapps -U1. Source code without dependencesadd your source code into the zip file, and set the entrypoint with-mpython3 -m zipapps -c -a entry.py -m entry:main -o app.pyzentry.pycould be a packagepackage_name-mformat ispackage.module:functionrun app.pyzpython3 app.pyz2. Source code with dependenceszipapps with requirementspython3 -m zipapps -c -a entry.py -m entry:main -o app.pyz bottlebottleis a pure-python lib which may not be unzipped-u AUTOor-u=*should be set for some.so/.pydlibssuch aspsutilnotice that the-u=*!=-u *you don't need to install requirements at runningensure the compatibility of the system environment and python versionor add-doflazy installmode to skip the compatibility problembut comes a long-timepip installprocess at the first running.run app.pyzpython3 app.pyzlibs with.pyd/.socaches will be unzipped to the./zipapps_cache/appby-u AUTO3. Virtual environmentszipapps with requirementspython3 -m zipapps -c -u AUTO -o venv.pyz -r requirements.txtrun entry.py with venv.pyzpython3 venv.pyz entry.pythe cache will be unzipped to./zipapps_cache/venvfor-uis not null4. Activate the.pyzenvironmentimport zipimport; zipimport.zipimporter('bottle.pyz').load_module("ensure_zipapps")automatically unzip cache, and add the path to sys.pathit can be run multiple timesif they are all pure-python code andno need to decompressimpory sys; sys.path.insert(0, "bottle.pyz")Command line usageBuild Argsmost common args:-cto compress files, only for python3.7+.-a xxx.pyto add some files/folders into the zipped file.-u=AUTORecommendedauto unzip the .pyd / .so filesor-u=*to unzip all the files-r requirements.txtinstall requirements withpip install-o my_app.pyzoutput the zipped file as given path-m app.__main__:mainentry point-p /usr/bin/python3set theshebangline-dRecommendedrequirements will be installed withpipwhile first running in the lazy install modezip file size will be very small, and the default unzip path isSELF/zipapps_cache/--clear-zipapps-cache,-czcClear the zipapps cache folder after running, but maybe failed for .pyd/.so files.Details:python3 -m zipapps -h-h, --helpshow the simple doc--includes, --add, -aThe given paths will be copied tocache_pathwhile packaging, which can be used while running. The path strings will be splited by ",".such asmy_package_dir,my_module.py,my_config.jsonoften used for libs not frompypior some special config filestheoutputarg ofzipapps.create_app--output, -oThe path of the output file, defaults toapp.pyz.theoutputarg ofzipapps.create_app--python, -pThe path of the Python interpreter which will be set as theshebang line, defaults toNone.with shebang/usr/bin/python3you can run app with./app.pyzdirectly, no need forpython3 app.pyztheinterpreterarg ofzipapps.create_app--main, -mThe entry point function of the application, thevalid formatis:package.module:functionpackage.modulemodule:functionpackagethemainarg ofzipapps.create_appWARNING: If the--mainarg is set,python3 app.pyzwill not be able to used as venv likepython3 app.pyz xxx.py--compress, -cBooleanvalue, compress files with the deflate method or not.thecompressedarg ofzipapps.create_app--unzip, -uThe names which need to be unzipped while running, splited by ","without ext, such asbottle,aiohttp, or the complete path likebin/bottle.py,temp.py. For.so/.pydfiles(which can not be loaded by zipimport), or packages with operations of static files.if unzip is set to "*", then will unzip all files and folders.if unzip is set toAUTO, then will add the.pydand.sofiles automatically.Can be overwrite with environment variableZIPAPPS_UNZIPtheunziparg ofzipapps.create_app--unzip-exclude, -ueThe opposite of--unzip/-uwhich will not be unzipped, should be used with--unzip/-u.Can be overwrite with environment variableZIPAPPS_UNZIP_EXCLUDE--unzip-path, -up3. Ifunziparg is not null, cache files will be unzipped to the given path while running. Defaults tozipapps_cache, support some internal variables as runtime args:$TEMP/$HOME/$SELF/$PID/$CWDas prefix, for example$HOME/zipapps_cacheTEMPmeanstempfile.gettempdir()HOMEmeansPath.home()SELFmeans.pyzfile path.$PIDmeansos.getpid()$CWDmeansPath.cwd()And you can alsooverwriteit with environment variables:ZIPAPPS_CACHEorUNZIP_PATHtheunzip_patharg ofzipapps.create_app-cc, --pyc, --compile, --compiledCompile .py to .pyc for fast import, but zipapp does not work unless you unzip it(so NOT very useful).thecompiledarg ofzipapps.create_app--cache-path, --source-dir, -cpThe cache path of zipapps to store site-packages andincludesfiles. If not set, will create and clean-up in TEMP dir automately.thecache_patharg ofzipapps.create_app--shell, -sOnly whilemainis not set, used for shell=True insubprocess.run.very rarely used, because extra sub-process is not welcometheshellarg ofzipapps.create_app--main-shell, -ssOnly formainis not null, callmainwithsubprocess.Popen:python -c "import a.b;a.b.c()". This is used forpsutilImportError of DLL load.very rarely usedtoothemain_shellarg ofzipapps.create_app--strict-python-path, -sppBooleanvalue. Ignore global PYTHONPATH, only usezipapps_cacheandapp.pyz.theignore_system_python_patharg ofzipapps.create_app-b, --build-idThe string to skip duplicate builds, it can be the paths of files/folders which splited by ",", then the modify time will be used as build_id. If build_id contains*, will useglobfunction to get paths. For example, you can set requirements.txt as your build_id bypython3 -m zipapps -b requirements.txt -r requirements.txtwhen you use pyz as venv.very rarely usedtoo toothebuild_idarg ofzipapps.create_app--zipapps, --env-pathsDefault--zipappsarg if it is not given while running. Support $TEMP/$HOME/$SELF/$PID/$CWD prefix.--delay, -d, --lazy-pip, --lazy-install, --lazy-pip-installInstall packages with pip while first running, which means requirements will not be install into pyz file.--ensure-pipAdd the ensurepip package to your pyz file, works forembed-python(windows) or other python versions withoutpipinstalled butlazy-installmode is enabled. [EXPERIMENTAL]--layer-modeLayer mode for theserverlessuse case,__main__.py / ensure_zipapps.py / activate_zipapps.pyfiles will not be set in this mode.--layer-mode-prefixOnly work while--layer-modeis set, will move the files in the given prefix folder.--clear-zipapps-cache, -czcClear the zipapps cache folder after running, but maybe failed for .pyd/.so files.--clear-zipapps-self, -czsClear the zipapps pyz file self after running.--chmodos.chmod(int(chmod, 8)) for unzip files with--chmod=777unix-like system only--dump-configDump zipapps build args into JSON string.A file path needed and-means stdout.--load-configLoad zipapps build args from a JSON file.--freeze-reqsFreeze package versions of pip args with venv, output to the given file path.-equals tostdoutlogs will be redirect tostderrBased onpip+venvwork folder istempfile.TemporaryDirectory, prefix='zipapps_'all the other (orunknown) args will be used bypip installsuch as-r requirements.txtsuch asbottle aiohttpthepip_argsarg ofzipapps.create_appRuntime Argsavailable args while the.pyzis running--zipappsincluding some other pyz into PYTHONPATHoften be used asmultiple venv combinationfor examplebuildpython3 -m zipapps -o six.pyz sixpython3 -m zipapps -o psutil.pyz -u AUTO psutilpython3 -m zipapps -o bottle.pyz bottlerunpython3 six.pyz --zipapps=psutil.pyz,bottle.pyz -c "import psutil, bottle"--activate-zipapps/--ensure-zipappsto ensure the zipapps_cache folder but do nothinguse environment variables to reset build args while running, and custom it withENV_ALIASargthe upper names are environment variables'unzip': 'ZIPAPPS_UNZIP',
 'unzip_exclude': 'ZIPAPPS_UNZIP_EXCLUDE',
 'unzip_path': 'ZIPAPPS_CACHE',
 'ignore_system_python_path': 'STRICT_PYTHON_PATH',
 'python_version_slice': 'PYTHON_VERSION_SLICE',
 'clear_zipapps_cache': 'CLEAR_ZIPAPPS_CACHE',
 'clear_zipapps_self': 'CLEAR_ZIPAPPS_SELF',
 'unzip_chmod': 'UNZIP_CHMOD',When to Use it?Package your code(package or model) into one zipped file.Pure python code without any 3rd-party dependencies.Python code with 3rd-party dependencies installed together.Python code with requirements be not installed until running.[Recommended] Thelazy installmode by the arg-d.The dependences will be installed at the first running(only once).This iscross-platformandcross-python-versionfor their independent cache paths.Run with python interpreter from thevenvpath.which means the requirements(need to be unzipped) will be installed to thevenvfolder, not inpyzfile.buildyour package into onepyzfile with-m package.module:function -p /venv/bin/python.runthepyzfile with/venv/bin/python app.pyzor./app.pyz.Rapidly deploy stateless applicationsServerlesswith a ready layerDockeronly built once for a Python environmentwget http://S3_PATH/app.pyz && python3 app.pyzSpot instancesAWS or AliyunHadoop-Streamingmapper & reducer scriptsSimple deployment towards different servers withjenkins, or other CI/CD tools.Easy to uploads a cleanstandalonezip file.Share theapp.pyzto your friendssomeone has python installedor embedded pythonor use nuitkazipapps with nuitkaUse as a requirements zip path, or somevenvusages.inner the codeimport sys;sys.path.insert(0, 'app.pyz')with .so/.pyd?import activate_zipappsor run it directlypython3 app.pyz script.pyOther usages need to be found, and enjoy yourselfAdvanced UsageInspired byshivand with the differences.zipappsmay not always create the cache folder.pure-pythondependencies can be import directly without unzipped.unless your package includes the C language-based libraries or dynamic modules(.so/.pyd), such aspsutil.use the arg-u=AUTOor-u=*The default cache path is./zipapps_cacheinstead of theHOMEpath.One app name create cache folder only once.You can install requirements withpipwhile first running(not packaging) bylazy installmodereducing your.pyzfile size.cross-platform and cross-python-versionpython -m zipapps -c -d -a your-package -r requirements.txtMix multiplevenv.pyzfiles together.python -m app.pyz --zipapps=bottle.pyz,requests.pyzFreezeyour requirements.txtpython -m zipapps --freeze-reqs=requirements.lock -r requirements.txtClick here read more1. Package your script file with only built-ins functions.1.1 Code ofscript.pyprint('ok')1.2 build theapp.pyzpython3 -m zipapps -c -a script.py -m script -p /usr/bin/python31.3 run this apppython3 app.pyzor./app.pyzouputokDetails:-c:
    compress files, 7.6KB => 3.3KB
-a:
    add the script file to app.pyz, so you can use it while running
-m:
    set the entry_point, also can be set as `-m script:main` as long as you has the main function
-p:
    set the shebang line, so you can use `./app.pyz` instead of `python3 app.pyz`2. Package your package folder into one zip file.2.1 The packageexampleand the code of__main__.py└── example
    ├── __init__.py
    └── __main__.pydefmain():print('ok')if__name__=="__main__":main()2.2 build theexample.pyzpython3 -m zipapps -c -a example -o example.pyz -m example.main:main -p /usr/bin/python32.3 Run withpython3 example.pyzor./example.pyzoutputokDetails:-m:
    set the entry_point with format like `package.model:function`
-o:
    set the output file path, you can set it some other paths like `/home/centos/example.abc` and run with `python3 /home/centos/example.abc`
no more new args.3. Package your code with requirements (bottle).3.1 The packageexampleand the code of__main__.py└── example
        ├── __init__.py
        └── __main__.pydefmain():importbottleprint(bottle.__version__)if__name__=="__main__":main()3.2 build theexample.pyzwith requirements installedpython3 -m zipapps -c -a example -o example.pyz -m example.main:main bottle3.3 Run withpython3 example.pyzor./example.pyzOutput0.12.19Details:bottle:
    all the unhandled args (like `bottle`) will be used to `pip install`, so you can write `bottle` in requirements.txt and use like `-r requirements.txt`WARNING: if the requirements have.pyd/.sofiles, you should unzip them while running, and the pure python libs likebottleorrequestsno need to unzip anything. Read the 4th paragraph for more info.4. Package your code with the requirements which includes.pyd/.sofiles.4.1 The packageexampleand the code of__main__.py└── example
    ├── __init__.py
    └── __main__.pydefmain():importpsutilprint(psutil.__version__)if__name__=="__main__":main()4.2 build theexample.pyzwith requirements installedpython3 -m zipapps -c -a example -o example.pyz -m example.main:main -u AUTO -up TEMP/cache psutil4.3 Run withpython3 example.pyzor./example.pyzOutput5.8.0Details:-u:
    means the file or folder names you want to unzip while running. Here is the `AUTO`, will unzip the psutil package because of its .pyd or .so files included.
-up:
    the unzip path of cache folder. $TEMP/$HOME/$SELF/$PID/$CWD are the built-in runtime args, but for the stable usage you can ignore this arg then use `./zipapps_cache/example`. The cache will be refreshed while you rebuild this pyz.WARNING: unzip path can be overwrited byexport ZIPAPPS_CACHE=./xxxorexport UNZIP_PATH=./xxxwhile running.5. Package the requirements like a virtual environment without entry_point.5.1 Code ofscript.pyimportbottle,requestsprint(bottle.__version__,requests.__version__)5.2 build thevenv.pyzpython3 -m zipapps -c -o venv.pyz -p /usr/bin/python3 bottle requests5.3 Some use cases5.3.1 use thevenv.pyzlike a middlewarepython3 venv.pyz script.py5.3.2 use thevenv.pyzlike the interpreter./venv.pyz script.pyeven like is also validpython3 venv.pyz -c "import bottle,requests;print(bottle.__version__, requests.__version__)"5.3.3 use thebottlelib ofvenv.pyzin your normal codeimportsyssys.path.append('path_to_venv/venv.pyz')importbottleprint(bottle.__file__)5.3.3 use thepstuillib ofvenv.pyzin other normal codepython3 -m zipapps -c -o venv.pyz psutilimportsyssys.path.append('path_to_venv/psutil_venv.pyz')# need to activate the unzip action, there are 2 ways for the `.so/.pyd` libs# 1. use the default activate nameimportactivate_zipapps# 2. use a distinct lib name with file name for another venv filesys.path.append('path_to_venv/lxml_venv.pyz')importensure_lxml_venv# 2.1 or the old name# import ensure_zipapps_lxml_venvimportpsutilimportlxmlprint(psutil.__file__)print(lxml.__file__)Output0.12.19 2.25.1Details:No `-m` arg here, then the pyz file will do like an interpreter which contains the installed requirements.

So you can use it like this:
> python3 venv.pyz
>>> import bottle
>>> bottle.__file__6. Using multiple venv pyz files for your pyz model.6.1 Here isscript.pyagainimportbottle,requestsprint(bottle.__version__,requests.__version__)6.2 Build thescript.pyzpython3 -m zipapps -c -o script.pyz -a script.py -m script requests6.3 Build therequests.pyzandbottle.pyzrespectivelypython3 -m zipapps -c -o requests.pyz requestspython3 -m zipapps -c -o bottle.pyz bottle6.4 And now run thescript.pyzwith two requirementspython3 script.pyz --zipapps=bottle.pyz,requests.pyzOutput0.12.19 2.25.1Details:--zipapps:
    This arg will help you run some zipapp with given venv.pyz files, the paths is separated by commas.7. Package your code with lazy install mode, for a attempt of cross-platform.7.1 Here isscript.pyagainimportsixprint(six.__file__)7.2 Build thescript.pyz, this is very fast without downloading and installing 3rd packages.python3 -m zipapps -c -o script.pyz -a script.py -m script -d six7.3 Run this.pyzfile, and the requirements will be installed while first running.python3 script.pyzOutputLooking in indexes: https://pypi.xxx.com/simple/
Collecting six
Using cached https://xxx/packages/ee/ff/xxxx/six-1.15.0-py2.py3-none-any.whl (10 kB)
Installing collected packages: six
Successfully installed six-1.15.0
/tmp/zipapps_cache/script/_zipapps_lazy_pip/3.8/Linux/six.pyDetails:-d:
    Lazy install mode is useful for distributing your cross-platform apps.