Virtual environments in Python create isolated spaces where you can install packages without affecting your global Python installation or other projects. These isolated environments contain their own Python binary and package installations, ensuring dependency conflicts don't occur between projects.
# Create a virtual environment
python -m venv myenv
# Create with specific Python version
python3.10 -m venv myenv# Install virtualenv
pip install virtualenv
# Create environment
virtualenv myenv
# Create with specific Python version
virtualenv -p python3.10 myenv# Activate
myenv\Scripts\activate.bat
# Deactivate
deactivate# Check execution policy
Get-ExecutionPolicy
# If restricted, allow scripts to run (run as Administrator)
Set-ExecutionPolicy RemoteSigned
# Activate
.\myenv\Scripts\Activate.ps1
# Deactivate
deactivate
# Create and activate in one command
python -m venv myenv; .\myenv\Scripts\Activate.ps1
# List all environments in directory
Get-ChildItem -Directory | Where-Object {Test-Path "$_\Scripts\activate.ps1"} | Select-Object Name# Activate
source myenv/bin/activate
# Deactivate
deactivate# Install packages
pip install package_name
# Install from requirements file
pip install -r requirements.txt
# Generate requirements file
pip freeze > requirements.txt
# Update package
pip install --upgrade package_name# List installed packages
pip list
# Show environment info
pip -V # pip version
python -V # python version
# Remove virtual environment
# Just delete the environment directory
rm -rf myenv # Linux/macOS
rmdir /s /q myenv # Windows Command Prompt
Remove-Item -Recurse -Force myenv # PowerShell# Create .env file in project root
echo "DEBUG=True" > .env
# Access in Python
import os
debug = os.environ.get("DEBUG")
# Use with python-dotenv
pip install python-dotenv- Name Consistently - Use descriptive names for projects
- Git Integration - Add venv/ to .gitignore
- Requirements - Keep requirements.txt updated
- Document - Note Python version and key dependencies
- Isolate Projects - One environment per project
- Activation Fails: Check Python version compatibility
- PowerShell Execution Policy: Run
Set-ExecutionPolicy RemoteSignedas admin - Permission Issues: Use
--userflag with pip or run as admin/sudo - Path Problems: Ensure Python is in your PATH variable
- Dependency Conflicts: Try
pip install --upgrade -r requirements.txt