It is not easy to deploy a Python project in cross-platform and cross-machine. You need spend time to prepare requirements.txt and solve the package version conflict. If project can be processed into one command, running the command can start the project function, which looks reduce deploying time.
pex is just what you need.
How to use pex tool to patch your project into one command?
Demo project Patch Python fastapi server project into command
1. Create a virtual environment, if don't have. Then activate env
2. Install pex tool
pip install pex
3. Put all project code in a directory, e.g. in the demo project, it is "src"
4. Prepare entry function, e.g. in the demo, it is def run() in app.py, and import it in src/__init__.py
5. Prepare pyproject.toml. MUST: in [project.scripts], set adder = "app:run" (app:run is entry of program)
6. Run pex to patch (outside src/). server_cli.pex is output executable name (can be any, extention .pex not necessary)
pex . -o server_cli.pex -r requirements.txt -D src -c adder
7. Test command
# Start server
./server_cli.pex
# code call server endpoint
import requests
params = {
"msg": "u catch it?",
}
url = "http://0.0.0.0:8000"
rsp = requests.post(url, json = params)
rsp.json()
Output: {'msg': 'u catch it?', 'is_success': True}
In Python3, there is a tool, zipapp. But it has limitation:
Any files may be present in the ZIP archive, but importers are only invoked for .py and .pyc files. ZIP import of dynamic modules (.pyd, .so) is disallowed. https://stackoverflow.com/questions/73040963/modulenotfound-exception-with-zipapp-and-compiled-c-code
For example, when zipapp langchain, it report orjson cannot loaded. Another noisy thing is that zipapp need downloads dependency to you project fold, which makes messy.
Many thanks to the project, pex_simple_cli.