Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

zipapp - จัดการ Executable Python Zip Archives

โมดูล zipapp ถูกเพิ่มใน Python Standard Library ตั้งแต่เวอร์ชัน 3.5 ใช้จัดการการสร้างไฟล์ Zip ที่มีโค้ด Python ซึ่งสามารถรันได้โดยตรงด้วย Python Interpreter โมดูลนี้มีทั้ง Command-Line Interface และ Programming Interface

การใช้งานผ่าน Command Line

ต้องมีโฟลเดอร์ที่มีโมดูลพร้อมฟังก์ชัน main()

python -m zipapp myapp -m "example:main"

โฟลเดอร์ myapp ต้องมี example.py ที่มีฟังก์ชัน main()

สร้าง example.py

def main():
    print('Hello World')

if __name__ == '__main__':
    main()

เมื่อรันคำสั่ง จะสร้าง myapp.pyz สามารถรันได้โดยตรง:

python myapp.pyz
Hello World

Command Line Options

  • -o <output>, --output=<output>: ระบุชื่อไฟล์ Output (Default: .pyz)
  • -p <interpreter>, --python=<interpreter>: ระบุ Interpreter ให้ชัดเจน
  • -c, --compress: บีบอัดด้วย Deflate Method ลดขนาดไฟล์

Programming Interface

  • zipapp.create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False): สร้าง Application Archive จาก Source Folder
  • zipapp.get_interpreter(archive): คืน Interpreter ที่ระบุใน Shebang (#!) ของ Archive

ตัวอย่างการใช้งานทางโปรแกรม

import zipapp
zipapp.create_archive('myapp', 'myapp.pyz', interpreter='/usr/bin/env python3')