Python pip and Virtual Environments

Isolate each project's packages with venv, install with python -m pip, and record dependencies so others can reproduce your setup.

Lesson 57 of 107Intermediate12 min read

A virtual environment is a project folder with its own Python interpreter link and its own installed packages, separate from every other project and from the system Python. pip installs packages into whichever environment is active. Together they let one project use Flask 3 and another Flask 2 on the same computer without conflict.

Terminal
python -m venv .venv                 # create
source .venv/bin/activate            # activate (macOS/Linux)
.venv\Scripts\activate               # activate (Windows)
python -m pip install requests       # install into .venv
python -m pip freeze > requirements.txt

This lesson explains what a virtual environment isolates, how to make sure pip installs into the right Python, how to record and reproduce dependencies, and how activation works. The modules lesson introduced pip; here you'll learn the workflow in depth. The examples set up a project for a weather station dashboard.

Environment isolation

Create an environment with the built-in venv module, usually in a folder named .venv inside the project:

Terminal
python -m venv .venv

The folder contains a pyvenv.cfg file, a link or copy of the Python executable, a scripts folder (bin on macOS and Linux, Scripts on Windows) and an empty site-packages folder where packages will be installed. Packages installed while it's in use don't affect any other environment, and deleting the folder removes them all.

A virtual environment isolates Python packages, nothing else. It isn't a container or a sandbox: code still runs with your user's permissions and can read your files and use the network. It also doesn't choose a Python version; it uses the version that created it. To run a different version, create the environment with that interpreter, for example py -3.12 -m venv .venv on Windows or python3.12 -m venv .venv elsewhere.

Interpreter selection

Most "I installed it but Python says ModuleNotFoundError" problems come from pip installing into a different Python than the one running your code. Two habits prevent it:

  1. Run pip through the interpreter you mean: python -m pip install requests. This always installs into the environment of that python.
  2. Check which interpreter is running:
Python
import sys
print(sys.executable)                 # full path to the running interpreter
print(sys.prefix != sys.base_prefix)  # True inside a virtual environment

A bare pip command is found through your PATH and may belong to another Python installation, especially on machines with several versions. Editors need the same care: in VS Code, choose "Python: Select Interpreter" and pick the .venv interpreter, or the editor will run your code with a different Python.

Installation records

A project's dependencies should be written down so that you, a colleague or a server can recreate the environment exactly:

Terminal
python -m pip install requests "flask>=3,<4"
python -m pip freeze > requirements.txt     # every installed package with exact versions
python -m pip install -r requirements.txt   # reproduce elsewhere

pip freeze pins exact versions (requests==2.32.3), including dependencies of your dependencies. That's ideal for reproducing an application. Unpinned requirements such as plain requests install whatever is newest on the day, so the same file can produce different environments months apart, sometimes with breaking changes.

Many projects keep a short hand-written list of direct dependencies with version ranges, plus a generated lock file of exact versions; tools such as pip-tools, Poetry and uv automate this. The dependency management lesson compares them.

Activation and cleanup

Activating an environment changes your shell's PATH so that python and pip refer to the environment's copies, and usually shows (.venv) in the prompt:

ShellActivate
macOS / Linux (bash, zsh)source .venv/bin/activate
Windows PowerShell.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat

deactivate returns to the normal shell. Activation is a convenience, not a requirement: running .venv/bin/python app.py (or .venv\Scripts\python.exe app.py) uses the environment directly, which is how scripts, cron jobs and services usually do it. On Windows, PowerShell may block the activation script; Set-ExecutionPolicy -Scope CurrentUser RemoteSigned allows it.

Add .venv/ to .gitignore. Environments contain machine-specific paths and binaries, so they shouldn't be committed or copied between computers; commit requirements.txt and recreate the environment instead. To start fresh, delete the folder and run the setup commands again.

Independent practice and a worked check

Task: create .venv, install a dependency, record its specification and reproduce the project in a second environment. On macOS or Linux:

Terminal
python -m venv .venv
source .venv/bin/activate
python -m pip install "requests>=2.31"
python -m pip freeze > requirements.txt
deactivate

python -m venv .venv-check
.venv-check/bin/python -m pip install -r requirements.txt
.venv-check/bin/python -c "import requests; print(requests.__version__)"

On Windows, replace source .venv/bin/activate with .venv\Scripts\activate and .venv-check/bin/python with .venv-check\Scripts\python.exe. The second environment ends up with the same versions, proving requirements.txt is complete. Delete .venv-check afterwards. For the worked check, the form that selects pip for a chosen interpreter is python -m pip.

Reference and next practice

The Python documentation covers venv and the guide to installing packages. Continue with dependency management and environment configuration. Practise with the Python exercises and Python quiz.

pip and Virtual Environments Summary

  • Environment isolation: venv creates a project environment with its own installed package set.
  • Interpreter selection: python -m pip runs pip associated with that interpreter.
  • Installation records: A requirements file records dependency specifications for a reproducible setup.
  • Activation and cleanup: Activation adjusts shell command lookup, and environments can also be used through their executable paths.

pip and Virtual Environments Examples

Each example shows the code, the output it produces and what each part does.

Example 1

pip and Virtual Environments in a small program

Run this inside and outside an activated environment to see the difference. The output depends on your machine: the first line shows the interpreter's file name, such as python or python.exe, and the second shows True only inside a virtual environment.

Python
import sys
from pathlib import Path
print(Path(sys.executable).name)
print(sys.prefix != sys.base_prefix)
Line-by-line explanation
  1. Line 3sys.executable is the full path of the running interpreter; .name keeps just the file name.
  2. Line 4Inside a virtual environment, sys.prefix points to the environment while sys.base_prefix points to the Python it was created from.
Example 2

Checking which packages an environment has

  • Your output depends on your setup: the pip version varies, and the first line says "no" if no environment is active.
Python
import sys
from importlib import metadata

in_venv = sys.prefix != sys.base_prefix
print("Virtual environment:", "yes" if in_venv else "no")

for package in ["pip", "surely-not-installed-xyz"]:
    try:
        version = metadata.version(package)
        print(package, "is installed, version", version.split(".")[0] + ".x")
    except metadata.PackageNotFoundError:
        print(package, "is not installed in this environment")
Output
Virtual environment: yes
pip is installed, version 26.x
surely-not-installed-xyz is not installed in this environment
Line-by-line explanation
  1. Line 4The same check as before, now as a readable message.
  2. Lines 7 to 11importlib.metadata.version() reports an installed package's version without importing it; the example shows only the major version.

Common pip and Virtual Environments Mistakes

Installing with a pip that belongs to another Python

Don't
pip install requests          # may install into a different Python
python app.py                 # ModuleNotFoundError: No module named 'requests'
Do
python -m pip install requests
python app.py

python -m pip guarantees the package goes into the interpreter you then use to run the app.

Committing the virtual environment folder

Don't
git add .venv            # thousands of machine-specific files
Do
echo ".venv/" >> .gitignore
git add requirements.txt

pip and Virtual Environments in Real Projects

Virtual environments in team workflows

A typical Python project README starts with the same three commands: create .venv, activate it, install from requirements.txt (or pyproject.toml). Continuous integration services run the same steps on every push, which proves the recorded dependencies are complete. Docker images often install requirements into the image instead of a venv, but the requirements file is the same.

Newer tools wrap the workflow: uv venv and uv pip install are much faster drop-in replacements, Poetry and Hatch manage environments per project automatically, and pipx installs command-line tools such as Black or Ruff into their own isolated environments so they don't clash with project dependencies.

pip and Virtual Environments FAQ

Why do I need a virtual environment in Python?

Different projects need different package versions, and installing everything into one global Python leads to conflicts and makes it unclear what a project depends on. A virtual environment gives each project its own packages and makes its setup reproducible.

What is the difference between venv and virtualenv?

venv is built into Python 3.3+ and is enough for most projects. virtualenv is an older third-party tool with a few extra features and faster creation. Both produce similar environments.

How do I activate a virtual environment on Windows?

In PowerShell run .venv\Scripts\Activate.ps1; in Command Prompt run .venv\Scripts\activate.bat. If PowerShell refuses to run scripts, allow them for your user with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.

Should I commit my venv folder to Git?

No. Add .venv/ to .gitignore and commit requirements.txt or pyproject.toml instead. Environments contain absolute paths and platform-specific files that won't work on another machine.

How do I know if I'm inside a virtual environment?

The prompt usually shows (.venv) when one is activated. From Python, sys.prefix != sys.base_prefix is True inside a virtual environment, and sys.executable shows the interpreter's full path.

pip and Virtual Environments Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which form selects pip for a chosen Python interpreter?

Multiple choicemedium

Which review concern is valid for pip and virtual environments?

pip and Virtual Environments Quiz

2 questions to check what you learned.

  1. Which form selects pip for a chosen Python interpreter?

    • An unrelated pip executable
    • python -m pip
    • Python ignores the distinction
  2. Which statement correctly describes installation records?

    • A requirements file records dependency specifications for a reproducible setup.
    • Only the example output matters, not the rule
    • Every operation has the same behavior