Sub topic 2
Installing and Uninstalling Packages with `python -m pip`
Assume you can run Python commands in a terminal and have an activated virtual environment. pip is Python’s package installer. Running it as python -m pip ensures that pip belongs to the same interpreter as python.
Install and uninstall packages
Install a package by naming it:
python -m pip install requestsYou can remove it later:
python -m pip uninstall requestspip may ask for confirmation before removing the package and its files. Installing into an activated virtual environment keeps the package separate from other projects.
Pinning and constraining versions
A version specifier controls which releases pip may install.
python -m pip install "requests>=2.31,<3"
python -m pip install "requests==2.32.3"The first command allows supported 2.x releases from 2.31 onward. The second pins the package to one exact release. Quoting the argument prevents some shells from interpreting characters such as <.
A constraint file limits choices without directly requesting packages:
# constraints.txt
requests==2.32.3
urllib3<3Use it with a requirements file:
python -m pip install -r requirements.txt -c constraints.txtInspect and upgrade packages
List packages installed in the active environment:
python -m pip list
python -m pip show requests
python -m pip check
python -m pip install --upgrade pippip show displays metadata such as the installation path and dependencies. pip check reports missing or incompatible dependencies.
Record and recreate an environment
A requirements file is a text file listing packages and versions. Record the current environment:
python -m pip freeze > requirements.txtCreate another environment, then install the recorded set:
python3 -m venv .venv-new
.venv-new/bin/python -m pip install -r requirements.txtpip freeze records exact versions, which makes the recreation predictable for the same platform and Python version.
Exercise
Which command best verifies that pip installs into the interpreter running your project?
Show answer
Run python -m pip --version and check that its path belongs to the intended environment.