Installing Packages With pip

There are two ways of installing packages using pip, the most used Python package manager.

Manual Installation

We can use pip to install packages inside our newly created environment. Pip is installed inside your virtual environment by default. Because everything is installed locally, you don’t need to become a superuser with sudo or su.

To install simplejson, simply use:

$ pip install simplejson

And to upgrade pip to the latest version, you can use pip too since it’s just another package inside your venv:

$ pip install --upgrade pip

Using a requirements.txt file

In a virtual environment, it’s a good habit to install specific versions of packages. It ensures that you reap the full benefits of using virtual environments in the first place. After all, we do this to make sure our software always works as intended by pinning down specific dependency versions.

A requirements.txt file contains a very simple list of dependencies, one per line. In its most simple form, it could look like this:

simplejson
chardet

But what we really want is to pin the versions. That’s not hard either:

chardet==3.0.4
simplejson==3.17.0

You can also relax these constraints a little, by using >= and <=, or even a combination of those:

chardet>=3.0.0,<=3.1.0
simplejson>=3.17.0

How do you know what range to use? Unfortunately there are no rules to this. You will have to read the release notes and such from the package in question.

You can make your life a little easier by creating your requirements file using pip’s freeze option. First write your software and install all the requirements you need as you go with pip. Once you’re done, simply use the following command:

$ pip freeze > requirements.txt

Pip will create a requirements file with all the currently installed dependencies, including version numbers. Neat!

Finally, to install all the dependencies listed in this file, use:

pip install -r requirements.txt


If you liked this page, please share it with a fellow learner: