Sub topic 14
Installing packages with pip
This chapter covers how to install third-party packages with pip, check what is installed, and record dependencies so someone else can recreate your setup. It assumes you already have these skills from earlier chapters:
- You can run
pythonorpython3from a terminal. - You can create and activate a virtual environment with
venv. - You can run a script file.
What pip is and where packages come from
pip is the package installer that ships with Python. A package is a bundle of code that someone else wrote, such as requests for making HTTP requests. By default, pip downloads packages from the Python Package Index (PyPI), a public repository at pypi.org. Anyone can publish to PyPI, so treat an unfamiliar package name with the same care you would give any code you download.
A package is installed into one specific Python environment. Each interpreter has its own site-packages directory, and Python looks there when it runs import requests. A virtual environment has its own site-packages, which is why isolating a project keeps its dependencies separate from every other project.
Run pip through the interpreter
You can type pip install requests, but the safer habit is python -m pip install requests. The -m flag tells Python to run a module as a program. Here the module is pip, and it runs inside the interpreter you named. A bare pip command is found through your PATH and may belong to a different Python than the python command you use to run scripts. That mismatch is the most common reason a package installs without errors and then fails to import.
With a virtual environment active, both forms normally point to the environment. The python -m pip form removes the doubt. You can confirm which interpreter and which pip you are using:
python -c "import sys; print(sys.executable)"
python -m pip --version
# On Windows without an active environment, use: py -m pip --versionThe second command prints the pip version and the path of the site-packages directory it will install into. If that path is not inside your .venv folder while the environment is active, stop and fix that before installing anything.
Install, inspect, upgrade, and remove
This sequence creates an environment, installs a package, and inspects the result:
python3 -m venv .venv
source .venv/bin/activate
# On Windows (Command Prompt): .venv\Scripts\activate.bat
# On Windows (PowerShell): .venv\Scripts\Activate.ps1
python -m pip install requests
python -m pip list
python -m pip show requestspip install requests also installs the packages that requests depends on, such as urllib3 and certifi. These are called transitive dependencies. pip list shows everything in the environment, including them. pip show requests prints the version, the location on disk, and two fields worth reading: Requires (what it needs) and Required-by (what in this environment needs it).
Once the package is installed, this script uses it:
import requests
response = requests.get("https://example.com", timeout=10)
print(response.status_code)
print(response.headers["content-type"])Save it as fetch.py and run python fetch.py with the environment active. It should print 200 followed by a content type such as text/html. Always pass timeout, because requests waits indefinitely by default.
The commands you will use most:
| Task | Command |
|---|---|
| Install the newest compatible version | `python -m pip install requests` |
| Install an exact version | `python -m pip install requests==2.32.3` |
| Upgrade an installed package | `python -m pip install --upgrade requests` |
| Remove a package | `python -m pip uninstall requests` |
| List installed packages | `python -m pip list` |
| List packages that have newer versions | `python -m pip list --outdated` |
| Show details for one package | `python -m pip show requests` |
Uninstalling a package does not remove its dependencies. If you want a clean slate, deleting the .venv folder and recreating it is simpler than removing packages one by one.
Version specifiers
A version specifier is the text after the package name that limits which versions pip may choose. These are the forms you will see:
| Specifier | Meaning |
|---|---|
| `requests` | Any version; pip picks the newest compatible one |
| `requests==2.32.3` | Exactly this version |
| `requests>=2.31` | This version or newer |
| `requests>=2.31,<3` | Newer than 2.31 but below 3 |
| `requests~=2.31` | Compatible release: at least 2.31, below 3.0 |
Quote any specifier that contains < or > on the command line, because the shell treats those characters as redirection:
python -m pip install "requests>=2.31,<3"Without the quotes, the shell would write the output of pip install requests into a file named 3 and silently ignore the version limit.
Record dependencies in requirements.txt
A requirements.txt file lists the packages a project needs, one per line. Anyone can then recreate your environment with one command. The usual workflow is:
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txtpip freeze prints every installed package with its exact version, in name==version form. The first command saves that list. The second command installs from it, and you would run it in a fresh environment on another machine.
Here is a trade-off to know about. pip freeze captures transitive dependencies too, so the file pins everything exactly. That gives reproducible installs, but the file becomes long and hard to read, and it is difficult to tell which lines you chose and which came along as dependencies. Many projects therefore keep a short hand-written file of direct dependencies with loose specifiers, and generate a fully pinned file from it for deployment. For a first project, pip freeze is fine.
Wheels, source distributions, and why installs sometimes compile
PyPI serves two kinds of files. A wheel (.whl) is a prebuilt package that pip simply unpacks, so it installs fast and needs no compiler. A source distribution contains the source code, and pip must build it first. Wheels exist for specific Python versions and platforms. If none matches your interpreter, pip falls back to the source distribution. For packages with compiled C code, that build can fail with long compiler errors.
The usual cause is a very new Python release for which the package author has not yet published wheels. If you see a wall of compiler output, check the last lines first. Often the fix is to upgrade pip with python -m pip install --upgrade pip, to use a slightly older Python version, or to wait for the package to publish a wheel.
Common errors and what they mean
| Message or symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError: No module named 'requests'` after installing | pip and `python` belong to different interpreters, or the environment is not active | Activate the environment and install with `python -m pip` |
| `error: externally-managed-environment` | Your operating system or Homebrew marks its own Python as off limits for pip | Create a virtual environment and install there |
| `Permission denied` or access errors | Trying to write into a system-owned Python | Use a virtual environment; do not use `sudo pip` |
| `No matching distribution found for ...` | Misspelled name, a version that does not exist, or no build for your Python version | Check the spelling on pypi.org and the version list |
| `pip: command not found` | pip is not on PATH | Use `python -m pip` |
| SSL or connection errors | Proxy, firewall, or no network | Check your connection; ask your network administrator about proxy settings |
Habits that prevent most problems
- Create one virtual environment per project and keep it inside the project folder.
- Install with
python -m pip, never a barepip. - Check
python -m pip --versionwhen something behaves oddly. - Commit
requirements.txtto version control, but not the.venvfolder. The environment is easy to recreate, and it contains paths specific to your machine. - Install only packages whose names you have verified on pypi.org. Look-alike names exist that are designed to catch typing mistakes.
Exercise
You activated .venv, ran pip install requests, and your script still fails with ModuleNotFoundError: No module named 'requests'. Name two checks that find the cause, and give the command you should have used to install the package.
Show answer
First, run python -c "import sys; print(sys.executable)" to see which interpreter runs your script, and run python -m pip --version to see where pip installs. If the paths are not both inside .venv, the bare pip command belongs to a different Python than python, or the environment is not active. Install with python -m pip install requests so pip runs inside the same interpreter that runs the script.
Exercise
What does the command python -m pip install requests>=2.31 do in a Linux or macOS shell, and how do you write it correctly?
Show answer
The shell reads > as output redirection, so it runs pip install requests and writes the output to a file named =2.31. The version limit is ignored. Quote the specifier: python -m pip install "requests>=2.31".