Virtual Environments
A virtual environment is an isolated Python environment that allows you to install packages separately for different projects. This prevents conflicts between project dependencies.
Why Use Virtual Environments?
- Dependency Isolation: Each project has its own packages
- Version Control: Different projects can use different package versions
- Clean System: Keeps your system Python installation clean
- Reproducibility: Easy to recreate project environments
- No Conflicts: Avoids package version conflicts
Creating a Virtual Environment
Using venv (Recommended)
python -m venv myenvThis creates a directory myenv with:
- Python interpreter
- pip
- Standard library
- Site-packages directory
Using virtualenv (Alternative)
pip install virtualenvvirtualenv myenvActivating a Virtual Environment
Windows
myenv\Scripts\activateLinux/Mac
source myenv/bin/activateWhen activated, your prompt will show the environment name:
(myenv) C:\Users\YourName>Deactivating a Virtual Environment
deactivateWorking with Virtual Environments
Install Packages in Virtual Environment
# Activate firstsource myenv/bin/activate # Linux/Mac# ormyenv\Scripts\activate # Windows
# Then install packagespip install requestspip install numpyList Installed Packages
pip listCreate Requirements File
pip freeze > requirements.txtInstall from Requirements
pip install -r requirements.txtVirtual Environment Best Practices
- One per project: Create a separate virtual environment for each project
- Name clearly: Use descriptive names like
project_name_env - Add to .gitignore: Don’t commit virtual environments to git
- Document dependencies: Always maintain requirements.txt
- Recreate when needed: If environment gets corrupted, recreate it
Project Structure with Virtual Environment
my_project/ .gitignore # Excludes venv/ requirements.txt README.md venv/ # Virtual environment (not committed) src/ my_code.py tests/ test_code.py.gitignore Example
# Virtual environmentsvenv/env/ENV/.venv
# Python cache__pycache__/*.pyc*.pyo*.pyd
# Requirements# Keep requirements.txt, ignore othersRecreating a Virtual Environment
If you need to recreate an environment:
# Remove old environmentrm -rf myenv # Linux/Macrmdir /s myenv # Windows
# Create new environmentpython -m venv myenv
# Activatesource myenv/bin/activate # Linux/Macmyenv\Scripts\activate # Windows
# Install dependenciespip install -r requirements.txtVirtual Environment Tools
venv (Built-in)
python -m venv myenvvirtualenv
pip install virtualenvvirtualenv myenvconda (Anaconda)
conda create -n myenv python=3.9conda activate myenvCommon Workflow
Create project directory
Terminal window mkdir my_projectcd my_projectCreate virtual environment
Terminal window python -m venv venvActivate virtual environment
Terminal window source venv/bin/activate # Linux/Macvenv\Scripts\activate # WindowsInstall packages
Terminal window pip install package_nameCreate requirements.txt
Terminal window pip freeze > requirements.txtWork on project
Terminal window python my_script.pyDeactivate when done
Terminal window deactivate
Troubleshooting
Virtual Environment Not Activating
Check Python installation:
python --versionwhich python # Linux/Macwhere python # WindowsPackages Not Found After Activation
Make sure virtual environment is activated:
which python # Should show venv pathPermission Errors
On Linux/Mac, you might need to set execute permissions:
chmod +x myenv/bin/activateExercises
Exercise 1: Virtual Environment Commands
Write the commands to: 1) Create a virtual environment named ‘myenv’, 2) Activate it (show both Windows and Linux/Mac versions), 3) Install a package ‘requests’, 4) Deactivate. Print these commands as a guide.
Virtual Environment Commands
commands = """1. python -m venv myenv2a. myenv\\Scripts\\activate (Windows)2b. source myenv/bin/activate (Linux/Mac)3. pip install requests4. deactivate"""
print(commands)Exercise 2: Requirements Workflow
After activating a virtual environment and installing packages, write the command to create a requirements.txt file. Then show how to install from it in a new environment.
Requirements Workflow
print("Create: pip freeze > requirements.txt")print("Install: pip install -r requirements.txt")