Sub topic 5
Installing and uninstalling packages with python -m pip
This chapter assumes you can create and activate a virtual environment with venv. It also assumes you can run commands in a terminal and know the difference between a Python script and a module. The commands below run inside an activated environment unless stated otherwise.
Why run pip as python -m pip
pip is a Python program that installs packages into one particular interpreter's site-packages directory. Typing pip install ... asks your shell to find some executable named pip on PATH. That executable may belong to a different interpreter than the python you use to run your code.
Typing python -m pip install ... removes that ambiguity. The -m flag tells the interpreter to run the pip module that belongs to it. Packages then land in the environment of that exact python.
python -m pip --version
python -c "import sys; print(sys.executable)"The first command prints the pip version and the path of the site-packages directory pip belongs to. The second prints the interpreter path. In a correctly activated environment, both paths point inside your .venv directory. If they do not, stop and fix that before installing anything.
On Windows without an activated environment, py -m pip runs pip for the interpreter the py launcher selects. Inside an activated environment, python -m pip is the right form on all platforms.
Installing a package
The basic form is install followed by one or more project names.
python -m pip install requests
python -m pip install requests richpip looks the name up on the package index (PyPI by default). It chooses a release and finds the dependencies that release declares. It then downloads, builds if needed, and installs all of them.
What happens during an install
A wheel is a prebuilt archive that pip can unpack directly. A source distribution must be built first, which needs a compiler for packages with C extensions. Building is the usual reason an install fails on an unusual platform or a very new Python version.
pip records each installed package in a *.dist-info directory next to the code. pip list, pip show, and pip uninstall all read that metadata.
Choosing versions
Without a specifier, pip installs the newest release compatible with your Python version. To control the version, add a specifier directly after the name.
python -m pip install "requests==2.32.3"
python -m pip install "requests>=2.31,<3"Always quote a specifier that contains < or >. Unquoted, the shell treats them as redirection operators. pip install requests>=2.31 would install requests and write the output to a file named =2.31. A later chapter covers specifier syntax in full.
Installing from other sources
pip accepts more than index names. These forms are useful, but treat each source as code you are choosing to trust.
python -m pip install ./local-project
python -m pip install ./dist/mypkg-1.0-py3-none-any.whl
python -m pip install -r requirements.txt
python -m pip install "git+https://github.com/example/[email protected]"A local directory must contain a pyproject.toml (or a legacy setup.py). A -r file is a list of requirements, covered in a later chapter.
Installing again, upgrading, and downgrading
If the requirement is already satisfied, pip prints Requirement already satisfied and does nothing. This is true even when a newer release exists. To move to the newest version, use --upgrade (or -U).
python -m pip install --upgrade requests
python -m pip install "requests==2.31.0"The second command downgrades. When you give an exact version that differs from the installed one, pip replaces the installed copy.
--upgrade upgrades the named package and, by default, only the dependencies that no longer satisfy its requirements. --upgrade-strategy eager upgrades all dependencies too.
Previewing and controlling an install
Some options change what pip does without changing the command's purpose.
| Option | Effect |
|---|---|
| `--dry-run` | Resolve and report what would be installed, without installing. Available in pip 22.2 and later. |
| `--no-deps` | Install only the named packages and skip their dependencies. |
| `--force-reinstall` | Reinstall even if the requirement is already satisfied. |
| `--only-binary :all:` | Refuse source builds and accept only wheels. |
| `--no-cache-dir` | Ignore pip's download and wheel cache for this run. |
| `-v` | Show more detail, useful when a build fails. |
--no-deps is a trap. It produces an environment where the package is present but its dependencies are not, and the failure appears later as an ImportError. Use it only when you manage the dependencies yourself, and run python -m pip check afterward.
python -m pip install --dry-run "requests>=2.31,<3"Names you install versus names you import
The name given to pip install is the distribution name on the index. The name you use in import is the top-level module name. They often match, but not always.
| pip install | import |
|---|---|
| `requests` | `requests` |
| `Pillow` | `PIL` |
| `scikit-learn` | `sklearn` |
| `beautifulsoup4` | `bs4` |
| `PyYAML` | `yaml` |
pip compares distribution names after normalizing them. Case is ignored, and runs of -, _, and . are treated as the same separator. So Scikit_Learn and scikit-learn name the same project. When you are unsure which names a package provides, python -m pip show -f PACKAGE lists the installed files, including the top-level directory.
Uninstalling a package
python -m pip uninstall requests
python -m pip uninstall -y requests rich
python -m pip uninstall -r remove.txtWithout -y, pip lists the files it will remove and asks for confirmation. Pass -y in scripts.
Uninstalling removes only the package you name. Its dependencies stay installed, even if nothing else needs them. pip has no built-in "autoremove". Over a long project, an environment accumulates orphaned packages. This is one of the main reasons to rebuild environments from a requirements file instead of editing them forever. A later chapter covers that workflow.
Uninstall also does not touch other environments. A package installed in .venv and in the system Python is two separate installations. Removing one leaves the other.
python -m pip uninstall requests
python -c "import requests"After a successful uninstall, the second command fails with ModuleNotFoundError. That error confirms the package is gone from this interpreter.
Common errors
externally-managed-environment
Many Linux distributions and Homebrew Python mark the system installation as externally managed. Running pip install against it fails with error: externally-managed-environment. The message is correct: installing there could break system tools. The fix is to create and activate a virtual environment, not to add --break-system-packages.
No matching distribution found
ERROR: Could not find a version that satisfies the requirement foo==9.9
ERROR: No matching distribution found for foo==9.9Likely causes:
- The version does not exist.
- The name is misspelled.
- The release does not support your Python version.
- No wheel exists for your platform and
--only-binaryis set. - You have no network access, or a configured index is wrong.
Run python -m pip index versions foo to list the versions the index offers. This command is marked experimental, but it is handy for this check.
Dependency conflicts
pip's resolver refuses to install a set of requirements that cannot all be satisfied. It prints which packages demand incompatible versions. Reading that output closely is the fastest fix: relax one specifier, or choose a release of the top-level package that supports the other versions. Packages installed earlier can also conflict with a new install. In that case pip warns after the fact, and python -m pip check shows what is now inconsistent.
Permission denied
A PermissionError during install usually means pip is writing to a directory you do not own. This normally happens when the environment is not active and pip targets a system location. Do not respond with sudo pip. Activate the environment, then confirm with python -m pip --version.
--user inside a virtual environment
--user installs into your per-user directory. Inside a virtual environment, pip rejects it, because the environment is meant to hold the packages.
Verifying the result
After installing or uninstalling, confirm the state from the interpreter's point of view.
python -m pip show requests
python -c "import requests; print(requests.__version__, requests.__file__)"pip show reads metadata. The import line proves Python can load the module, and __file__ shows which copy it loaded. If that path is outside your environment, another interpreter or a PYTHONPATH entry is supplying the module.
Exercise
You run pip install "flask>=3" in an activated environment, and import flask then fails with ModuleNotFoundError. pip --version shows a path under /usr/lib/python3/dist-packages. What is the most likely cause, and what command should you use instead?
Show answer
The pip on PATH belongs to the system interpreter, not to the environment's python, so Flask was installed in the wrong place. Use python -m pip install "flask>=3", which installs into the interpreter that runs your code. Check with python -m pip --version.
Exercise
You install rich with python -m pip install rich, which also installs markdown-it-py and pygments as dependencies. You then run python -m pip uninstall -y rich. Which of the three packages remain installed, and how would you get a clean environment?
Show answer
markdown-it-py and pygments remain, because pip uninstalls only the named package and has no autoremove. To get a clean environment, delete the environment directory and rebuild it from your requirements file, or uninstall the leftover packages by name if you know nothing else needs them.
Exercise
Why does python -m pip install requests>=2.31 appear to succeed but create a file named =2.31 and install the unversioned latest release?
Show answer
The shell reads > as output redirection. It runs python -m pip install requests and writes its output to a file named =2.31. Quote the requirement: python -m pip install "requests>=2.31".