Home > python > Python equivalent of Java .jar files

Python equivalent of Java .jar files

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.

Advertisements
Categories: python Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: