How to Install Python Packages with pip

John John (304)
5 minutes

Rather than reinvent the wheel, a good Pythonista will make use of the many, many great third-party Python packages and frameworks. This guide will show you how to install packages with pip.

What is pip?

Pip is the package manager for Python. It helps us install, upgrade, and uninstall packages from the PyPI repository. If you haven't installed pip, follow our guide on how to install pip on all major platforms.

Posted in these interests:
h/python67 guides
h/code69 guides

To install the latest version of a package, type:

pip install AwesomePackage

If you want to install a specific version of a package use:

pip install AwesomePackage==2.0

The following will install any version of AwesomePackage greater than or equal to 1 and less than 2.

pip install "AwesomePackage>=1,<2"

This one is a little more complicated, but imagine you want to install a newer version of AwesomePackage that is compatible with AwesomePackage==2.1.2. This means you want AwesomePackage 2.1.x that is greater than 2.1.2.

pip install AwesomePackage~=2.1.2

I started with installing packages individually, but in most cases you'll actually want to install packages in bulk using a requirements.txt file.

Using everything we learned above, we can create a single file that lists all of the packages we want to use in our project.

So I'll create a file (usually located in the root of the project directory) called requirements.txt, and add the following:

AwesomePackage==2.0
SomeOtherPackage==1.0
XYZPackage==3.2.5

Now, after saving the file and exiting, we can install all of the packages together:

pip install -r requirements.txt

Why use requirements.txt?

There are a few obvious reasons to use a requirements.txt file.

  1. It provides a list of your projects dependencies.
  2. Other developers can easily install all required packages on their dev environments.
  3. It simplifies the installation process.

Pip freeze

To confirm the packages were installed you can use pip freeze.

pip freeze

Note: This will show all installed packages. Sometimes, the packages we list in requirements.txt will depend on other packages that will come along for the ride.

To look for specific packages, use grep:

pip freeze | grep "AwesomePackage"

A note on pinning versions

Your requirements.txt file doesn't have to include version numbers. It can look like this:

AwesomePackage
SomeOtherPackage
XYZPackage

This is a little bit dangerous. As soon as new versions of any of these packages are available, future builds will automatically include them. This could break your code. To remedy this situation, pin each package to a specific version and only upgrade packages intentionally.

John John (304)
5 minutes

The Python standard library includes a great set of modules, but many projects will require the use of third-party modules.