Créer un executable egg

Problem

In Java, you can distribute your project in JAR format. It is essentially a ZIP file with some metadata. The project can be launched easily:

$ java -jar project.jar

What is its Python equivalent? How to distribute a Python project (with several modules and packages) in a single file?

Solution

The following is based on this post, written by bheklilr. Thanks for the tip.

Let’s see the following project structure:

MyApp/
    MyApp.py          <--- Main script
    alibrary/
        __init__.py
        alibrary.py
        errors.py
    anotherlib/
        __init__.py
        another.py
        errors.py
    configs/
        config.json
        logging.json

Rename the main script to __main__.py and compress the project to a zip file. The extension can be .egg:

myapp.egg/             <--- technically, it's just a zip file
    __main__.py        <--- Renamed from MyApp.py
    alibrary/
        __init__.py
        alibrary.py
        errors.py
    anotherlib/
        __init__.py
        another.py
        errors.py
    configs/
        config.json
        logging.json

How to zip it? Enter the project directory (MyApp/) and use this command:

zip -r ../myapp.egg .

Now you can launch the .egg file just like you launch a Java .jar file:

$ python myapp.egg

You can also use command-line arguments that are passed to __main__.py.