Virtual Environments
Manage project dependencies and isolate Python environments
Why Virtual Environments?
- Isolate project dependencies from system Python
- Avoid version conflicts between projects
- Easy to share project requirements
- Keep global Python installation clean
# Virtual environments solve these problems:
# - Project A needs Django 3.2
# - Project B needs Django 4.0
# - Without venv, only one version can be installed globally
# - With venv, each project has its own isolated environment
Creating Virtual Environments
- Use venv module (built into Python 3.3+)
- Creates isolated Python environment in a folder
- Contains its own Python interpreter and packages
- Common convention: name folder 'venv' or '.venv'
# Create virtual environment
# Command: python -m venv myenv
# On Windows:
# python -m venv venv
# On Mac/Linux:
# python3 -m venv venv
# This creates a 'venv' folder with:
# - Python interpreter
# - pip package manager
# - Site-packages directory for installed packages
Activating Virtual Environments
- Must activate before using the environment
- Activation changes PATH to use venv's Python
- Different commands for Windows vs Mac/Linux
- Prompt usually shows (venv) when activated
# Activate virtual environment
# On Windows:
# venv\Scripts\activate
# On Mac/Linux:
# source venv/bin/activate
# After activation, your prompt shows:
# (venv) C:\Users\YourName\project>
# Deactivate when done:
# deactivate
Managing Dependencies
- Use pip to install packages in venv
- requirements.txt lists all dependencies
- pip freeze saves current packages
- Easy to recreate environment on another machine
# Install packages in activated venv
# pip install requests
# pip install django==4.0
# pip install pandas numpy matplotlib
# Save dependencies to file
# pip freeze > requirements.txt
# Install from requirements.txt
# pip install -r requirements.txt
# Example requirements.txt:
# requests==2.28.0
# django==4.0.0
# pandas==1.5.0
# Uninstall package
# pip uninstall requests