Virtual Environments & pip (Create, Activate, Freeze, Requirements) - Python Tutorial #27
Video: Virtual Environments & pip (Create, Activate, Freeze, Requirements) - Python Tutorial #27 by Taught by Celeste AI - AI Coding Coach
Watch full page →Virtual Environments & pip in Python: Create, Activate, Freeze, and Requirements
Virtual environments in Python allow you to isolate project dependencies, preventing conflicts between packages across projects. This tutorial covers creating and activating virtual environments using venv, managing packages with pip, and sharing dependencies through requirements.txt files for reproducible setups.
Code
# Create a new virtual environment named 'myenv'
python3 -m venv myenv
# Activate the virtual environment (Linux/macOS)
source myenv/bin/activate
# On Windows (PowerShell), activate with:
# .\myenv\Scripts\Activate.ps1
# Install a package inside the virtual environment
pip install requests
# List installed packages and their versions
pip list
# Freeze installed packages to a requirements file
pip freeze > requirements.txt
# Deactivate the virtual environment when done
deactivate
# To reproduce the environment on another machine:
# 1. Create and activate a new virtual environment
python3 -m venv myenv
source myenv/bin/activate
# 2. Install all dependencies from requirements.txt
pip install -r requirements.txt
Key Points
- Virtual environments isolate Python dependencies, avoiding version conflicts between projects.
- Create environments using
python3 -m venv <env-name>and activate them withsource <env-name>/bin/activate(or platform equivalent). - Use
pip installto add packages inside the environment, andpip freeze > requirements.txtto save exact versions. - Share your
requirements.txtfile to allow others to replicate the same environment withpip install -r requirements.txt. - Always deactivate the environment with
deactivatewhen finished to return to the global Python setup.