Python Packaging

How To Package Your Python Code

Directory Structure

First of all, you better adhere to a certain directory structure for your Python code. I like to use Cookie Cutter to create such structure for me. All you have to do is to install cookiecutter then type in the following command wherever you want to create your directory:


You may find additional Cookiecutter templates for Python packages here as well

Virtual Environment

This step is not a must, however, I find it useful in case you wanna test multiple versions of your code and do not want to contaminate your path with faulty code.

Install virtualenv if you haven't done that yet:

[sudo] pip install virtualenv

Then to create a virtual environment into a certain directory, type the following command while in that directory:

virtualenv venv

And after that, while inside the same directory, you need to activate your virtual environment as follows:

source venv/bin/activate

Now anytime you install new Python packages while in that directory, they will be installed in the virtual environment only, i.e. no system-wide installation. This makes it easy for you to test the Python package you are developing and see if it installs successfully without installing it on the whole system.

When done with the virtual environment, you may deactivate it as follows:


Local Installation

Once done writing your code and making sure the README and files are editted successfully, you may proceed with installing your code

While inside your virtual environment, you can invoke the following command to install the package inside your virtual environment:

python install

If you run the previous command while the virtual environment is deactivated, the package will be installed on your system, and not inside that specific environment.

You also can install the package with a symlink, so that changes to the source files will be reflected into your installed package by using the following command instead:

python develop

Publish your package to PyPI

You need to register your package first as follows:

python register

Then you have to create a source distribution in your dist folder, so that you can upload it to PyPI later on:

python sdist

Then you upload your Python code to PyPI as follows:

python sdist upload

Now, you or anyone else in the world can install your package on their system, or in their virtual environment, using the following command:


Maintaining Multiple Packages

If your project depends on multiple packages, rather than using pip to install them one by one, you can write them down in a requirements.txt file that looks like this.


Then you install (or upgrade) them all at once using the following command:

pip install -r requirements.txt

Share on Facebook Share on twitter