Python Virtual Environments

Introduction

Virtual environments are isolated Python installations that prevent package conflicts. They let you create project-specific dependencies without affecting your system Python. Every serious Python project uses them.

1. Creating a Virtual Environment

python -m venv venv
    

This creates a folder named venv/ containing an isolated Python setup.

2. Activating the Environment

Windows:

venv\Scripts\activate
    

macOS / Linux:

source venv/bin/activate
    

3. Deactivating the Environment

deactivate
    

4. Installing Packages Inside the Environment

pip install flask
pip install requests
    

5. Checking Installed Packages

pip list
    

6. Freezing Dependencies

Creates a file listing all installed packages.

pip freeze > requirements.txt
    

7. Installing from requirements.txt

pip install -r requirements.txt
    

8. Why Virtual Environments Matter

9. Using Different Python Versions

python3.12 -m venv venv312
python3.10 -m venv venv310
    

10. Virtual Envs in VS Code

VS Code auto-detects environments. To select manually:

Ctrl + Shift + P → "Python: Select Interpreter"
    

11. Requirements for Deployment

Servers typically run:

pip install -r requirements.txt
    

12. Using pipx for Global Tools

pipx install black
pipx install httpie
    

13. Common Mistakes

14. Adding venv to .gitignore

venv/
    

Summary