How do I install and manage third-party packages with pip?
· Category: Python Programming
Short answer
pip is Python's standard package installer. Use pip install package_name to install from PyPI, pip install -r requirements.txt for batch installation, and pip list or pip freeze to inspect installed packages.
Steps
- Install a package:
pip install requests. - Pin versions:
pip install requests==2.31.0. - Record dependencies:
pip freeze > requirements.txt. - Reproduce an environment:
pip install -r requirements.txt.
pip install numpy pandas
pip install --upgrade numpy
pip uninstall numpy
Tips
- Use virtual environments to isolate project dependencies.
- Prefer
pyproject.tomlorrequirements.inwith a tool likepip-toolsfor reproducible environments. pip install -e .installs a package in "editable" mode, useful during development.- Use
pip show package_nameto view metadata and dependencies of an installed package.
Common issues
- Installing packages into the system Python can break OS tools; always use a virtual environment.
- Conflicting dependencies between packages can be resolved with a lock file or a dependency manager like
poetryoruv. - Permission errors on Linux/macOS are usually fixed by using
--useror a virtual environment instead ofsudo pip.