Virtual Environments in Python
Virtual environments isolate project dependencies from the system Python.
Creating and activating
Use the built-in venv module.
python -m venv .venv
# activate
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows PowerShell: .venv\Scripts\Activate.ps1
Deactivate with deactivate.
Using the environment
Install packages locally to the environment.
pip install requests
pip list
Pin dependencies with pip freeze > requirements.txt and recreate with pip install -r requirements.txt.
Selecting interpreters
Editors/IDEs can select the venv interpreter (.venv/bin/python). Use python -m pip to ensure you target the right environment.
Multiple environments
Create separate environments per project; name with .venv for conventional tooling support.
Tools and alternatives
pipxfor isolated CLI toolsvirtualenv(faster env creation)condafor Python + native libs/data science stackspoetry/pipenvfor dependency management and virtualenvs
CI and deployment
Use venv to replicate production dependencies; cache pip downloads between builds.
Summary
- Use
python -m venv .venvper project, activate, thenpip install - Pin and reproduce via
requirements.txt; consider higher-level tools as needed