Python Virtual Environments and pip: A Beginner's Guide
Introduction
A virtual environment is an isolated copy of Python for a single project, so packages installed for one project can't conflict with another. This guide shows how to create and activate one, install packages with pip, and share your dependencies with others.
Prerequisites
- Python 3.8 or newer installed
- Access to a terminal or command prompt
Step-by-Step Guide
Step 1: Create a virtual environment
Run the built-in venv module inside your project folder. This creates a .venv folder with its own Python interpreter. On some systems the command is python3 instead of python.
python -m venv .venvStep 2: Activate the environment
Activation points your shell at the environment's interpreter and packages. The command depends on your operating system.
# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1Step 3: Install packages with pip
With the environment active, pip installs packages into it only, leaving your system Python untouched.
pip install requests
pip listStep 4: Save and restore dependencies
Record installed packages in requirements.txt so anyone can recreate the same environment.
pip freeze > requirements.txt
# later, in a fresh environment:
pip install -r requirements.txtStep 5: Leave the environment
When you're done, deactivate to return to your normal shell.
deactivateFAQs
- Should I commit the .venv folder to Git?
- No. Commit requirements.txt and add .venv to .gitignore. Each developer recreates the environment from the requirements file.
- What is the difference between venv and pip?
- venv creates the isolated environment. pip installs packages into whichever environment is currently active.
Summary
Create one virtual environment per project, activate it before installing anything, and keep a requirements.txt so your setup is reproducible on any machine.
Comments
Log in or create a free account to join the discussion.