Explain Codes LogoExplain Codes Logo

How to install multiple python packages at once using pip

python
pip-installation
requirements-file
virtual-environment
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

To install several Python packages in one fell swoop with pip, you can leverage chained package names or present a requirements.txt list:

Direct installation:

# We're going on a pip package tour! Hop in! pip install package1 package2 package3

Through a requirements.txt file:

# contents of `requirements.txt` file package1>=1.0.0 package2>=2.0.0 package3>=3.0.0 # command to install pip install -r requirements.txt

With these methods, you are not only utilizing pip effectively but also organizing your package management efficiently.

Customized installations

Often times, there can be a dependency on the versions of packages being used. In this case, you can use a requirements.txt file like this:

# "Orders up" for the barista at the pip cafe! numpy==1.19.3 pandas>=1.1.5,<1.2.0 requests>=2.25.0

Execute version-controlled installation:

pip install -r requirements.txt

The version of numpy installed will be exact, for pandas it will be the latest version which is 1.2.0 or lower, and for requests, it will be 2.25.0 or higher.

Nifty production tips

For production environments, it pays to consider the following when preparing a requirements.txt file:

  • Version pinning to avoid unexpected updates (use ==).
  • Specify compatible versions (use <=, >=, !=, ~=).
  • Test with the specified versions before deploying to the production environment.

This creates a predictable, stable and reliable requirements.txt which ensures a smooth roll-out and stability post-deployment.

Harness the power of a requirements file

Wouldn't it be great if you could generate a requirements.txt file from an existing environment? As easy as:

# Go-go gadget "freeze"! pip freeze > requirements.txt

This command neatly stacks every installed package, along with its buttery smooth version, into a text file. You'll find it incredibly useful when:

  • Migrating environments: Like importing your grandma's secret pie recipe into your new kitchen.
  • Version locking: Keeping things as they were. No unexpected "suprise features"!
  • Project documentation: Giving your teammates a map to the bounty of quick setup.

Gracefully handling installation issues

Should you encounter hiccups, here are some typical remedies:

  • Connectivity: Check your internet. Packages don't teleport (yet)!
  • Spelling: Don't get tripped up missing 'i's or mixing 'e's. Package names are often crafty.
  • Virtual environment: Best practise. Keeps everything neat and tidy. No permission issues, no conflicts.

Creating a virtual environment is as easy as pie:

python3 -m venv myenv source myenv/bin/activate

Then, just run pip commands in this isolated space. Neat, right?