Module zipapp (Python 3.5+) tạo file zip chứa code Python có thể chạy trực tiếp bằng interpreter.
Yêu cầu
- Thư mục chứa code (ví dụ
myapp/). - Module có hàm
main()(ví dụmyapp/example.py).
Tạo executable archive từ command line
python -m zipapp myapp -m "example:main"
Tạo file myapp.pyz. Chạy:
python myapp.pyz # Hello World
Ví dụ cấu trúc thư mục
myapp/ ├── example.py └── __init__.py (optional)
# example.py
def main():
print('Hello World')
if __name__ == '__main__':
main()
Tùy chọn command line
| Option | Mô tả |
|---|---|
-o, --output | Tên file xuất ra (mặc định .pyz) |
-p, --python | Chỉ định interpreter (shebang) |
-c, --compress | Nén deflate (giảm kích thước) |
API lập trình (Programmatic API)
import zipapp
# Tạo archive từ thư mục nguồn
zipapp.create_archive('myapp', 'myapp.pyz', interpreter='/usr/bin/env python3', compressed=True)
# Đọc interpreter từ archive
interpreter = zipapp.get_interpreter('myapp.pyz')
print(interpreter)
Ưu điểm
- Đóng gói ứng dụng đơn file, dễ phân phối.
- Không cần cài đặt package, chỉ cần Python interpreter.
- Hỗ trợ nén để giảm dung lượng.
Hạn chế
- Không hỗ trợ C extension (.so/.pyd).
- Không quản lý dependency (phải bundle sẵn hoặc yêu cầu cài đặt).
- Chỉ chạy được trên cùng architecture Python.
Alternatives
- PyInstaller, cx_Freeze, py2exe: Tạo executable native (.exe), bundle interpreter.
- shiv, pex: Tạo .pyz với dependency management tốt hơn.