PIP

Overview of the Standard Python Package Manager, PIP.

Introduction

The standard Python package manager is pip. It is ideal for quickly starting Python projects, like simple scripts or small projects with few dependencies. While capable of handling larger projects, tools like poetry are ideal for larger projects with complex dependencies.

The following notes assume:

  • Python 3

  • MacOS

  • An alias in bash profile to map python to python3.

Setup

The following is a step-by-step process for setting up a virtual environment in my-project and installing dependencies in it with pip.

  1. cd into your project directory.

cd my-project
  1. Create the virtual environment named env.

python -m venv env
  1. Activate the virtual environment.

source env/bin/activate
  1. Install dependencies.

pip install <PACKAGE_NAME>

Commands

The following is a list of common commands used when managing a project with pip.

Activate Virtual Environment

Deactivate Virtual Environment

Uninstall a Package

List Installed Packages

Create a requirements.txt File

Install Packages from a requirements.txt File

Pitfalls & Solutions

The following are common pitfalls when working with pip and their solutions.

I installed packages without activating my virtual environment.

To uninstall packages from your machine using the requirements.txt file in your project, make sure your virtual environment is not activated and run the following command:

To uninstall all global Python packages from your machine, make sure your virtual environment is not activated and run the following command:

How do I pin the versions of my project's dependencies?

To prevent dependency conflicts, it is recommended to create a requirements.txt file with pinned package versions. The following command is a way to automatically create a requirements.txt file from the packages installed in your virtual environment:

Can I disable pip when there is no virtual environment activated?

Yes. To require a virtual environment to be active when running pip commands, a config file can be used.

Run the following command to set require-virtualenv to True.

Now, the contents of ~/.config/pip/pip.conf should be:

If you ever need to get around this requirement, you can either temporarily set require-virtualenv to False, or prepend your pip commands as follows:

Last updated

Was this helpful?