Pip and Virtual Environments
Managing external libraries and keeping project dependencies isolated is crucial for stable Python development.
What is Pip?
Pip is the standard package manager for Python. It allows you to install and manage additional libraries and dependencies that are not part of the Python standard library.
Basic Commands
- Install a package:
Terminal window pip install camelcase - Uninstall a package:
Terminal window pip uninstall camelcase - List installed packages:
Terminal window pip list
Virtual Environments
A Virtual Environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
Using a virtual environment prevents version conflicts between different projects.
Creating a Virtual Environment
Python comes with a built-in module called venv to create virtual environments.
# Windowspython -m venv myenv
# macOS / Linuxpython3 -m venv myenvActivating the Environment
Once created, you must “activate” it to start using its isolated Python and Pip.
- Windows:
Terminal window myenv\Scripts\activate - macOS / Linux:
Terminal window source myenv/bin/activate
After activation, your terminal prompt will usually show the name of the environment in parentheses.
Deactivating
To stop using the virtual environment, simply run:
deactivateUsing requirements.txt
It is common practice to list all project dependencies in a file named requirements.txt.
- Generate the file:
Terminal window pip freeze > requirements.txt - Install from the file:
Terminal window pip install -r requirements.txt