Skip to content
Visual explainer 2h to learn 4 steps

Virtual environments & pip

Create a venv per project and pin dependencies in a requirements file.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 17 of 34

In short

A virtual environment is a private folder of installed packages for one project. pip installs packages into it, and a requirements.txt file records exact versions so anyone can recreate the same setup.

Think of it like this: A venv is a separate toolbox per project, so tools for one job never clash with another.

Explained simply

When you install a package with pip, it goes into a folder that Python searches when you import. If every project shares one folder, they also share versions. Project A needs version 1 of a library, project B needs version 2, and one of them breaks.

A virtual environment (venv) gives each project its own private folder of packages. You create it once inside the project, turn it on (activate it), and from then on pip installs into that folder only. Other projects never see those packages.

pip is the tool that downloads packages from PyPI, the Python Package Index, and installs them. pip freeze lists exactly what is installed with version numbers. Saving that list in requirements.txt lets anyone rebuild the same setup later with one command.

Think of the venv as disposable. If it ever gets messy, delete the .venv folder and recreate it from requirements.txt in a minute. That is also why you never commit .venv to Git: the requirements file is the recipe, the venv is just the cooked dish.

Press Play on a diagram to walk through it one step at a time.

LayersWhat your code runs on
  1. 1
    Your code

    import requests in main.py

  2. 2
    Project packages

    Installed by pip into .venv/site-packages

  3. 3
    venv Python

    .venv/bin/python, active after activate

  4. 4
    Base Python install

    The interpreter and standard library

  5. 5
    Operating system

    Windows, macOS or Linux

FlowRecreating an environment
  1. 1
    python -m venv .venv

    Create the environment once per project

  2. 2
    Activate

    source .venv/bin/activate or .venv\Scripts\activate

  3. 3
    pip install

    Add packages as you need them

  4. 4
    pip freeze

    Save versions to requirements.txt

  5. 5
    pip install -r

    Teammates rebuild the same environment

SequenceA teammate recreates your environment
You
Git repo
Teammate
PyPI
  1. 1pip freeze > requirements.txt
    You to You: pip freeze > requirements.txt
  2. 2Commit requirements.txt, not .venv
    You to Git repo: Commit requirements.txt, not .venv
  3. 3git clone
    Teammate to Git repo: git clone
  4. 4python -m venv .venv, activate
    Teammate to Teammate: python -m venv .venv, activate
  5. 5pip install -r requirements.txt
    Teammate to PyPI: pip install -r requirements.txt
  6. 6Same exact versions downloaded
    PyPI to Teammate: Same exact versions downloaded

In depth

What a venv actually contains

python -m venv .venv creates a small folder. Inside is pyvenv.cfg, a text file that points to the base Python it was made from. There is a bin folder (Scripts on Windows) with a python that refers back to the base interpreter, pip, and the activate scripts. And there is lib/python3.X/site-packages (Lib\site-packages on Windows), which starts almost empty.

When this python starts, it sees pyvenv.cfg and uses the venv's site-packages instead of the global one. The standard library still comes from the base install, so a venv is small.

Activation is less magic than it looks. It mostly puts the venv's bin folder first in your PATH and sets the VIRTUAL_ENV variable, so typing python or pip finds the venv's copies. You can skip activation entirely and run .venv/bin/python script.py directly, which is handy in cron jobs and systemd services. A venv stores absolute paths, so moving or renaming the folder breaks it; just recreate it.

MapInside .venv on Linux or macOS
.venv/
  • pyvenv.cfg
    • home = path to the base Python
    • version of Python used
  • bin/ (Scripts\ on Windows)
    • python, pip
    • activate scripts
    • Command-line tools you install
  • lib/python3.X/site-packages/
    • Packages pip installs
    • Starts nearly empty

Version specifiers and what pip install really does

You can ask pip for a version range. requests==2.32.3 pins one exact version. requests>=2.31 allows that or newer. requests>=2.31,<3 allows newer versions but not the next major one, which might break your code. requests~=2.32.0 means compatible release: at least 2.32.0 but below 2.33.

When you install a package, pip also installs its dependencies, and theirs. Installing requests brings in urllib3, idna, charset-normalizer and certifi. pip's resolver looks for a set of versions that satisfies every requirement at once. If none exists, it stops with a ResolutionImpossible error that names the conflicting packages.

Most packages download as wheels (.whl files), which are pre-built and install quickly. If no wheel matches your Python version and OS, pip falls back to building from source, which may need a compiler. That is a common reason installs fail on brand-new Python versions.

  • pip list shows installed packages; pip show requests shows details and dependencies
  • pip install --upgrade requests updates to the newest allowed version
  • pip uninstall requests does not remove its dependencies

requirements.txt done well

pip freeze > requirements.txt writes every installed package with an exact version, including indirect dependencies you never asked for. That is good for reproducibility: the same file gives the same environment next month. The downside is that it is hard to see which packages you actually chose.

A common improvement is to keep two files. requirements.in lists only your direct dependencies with loose ranges, like requests>=2.31. A tool such as pip-tools (pip-compile) or uv then resolves them into a fully pinned requirements.txt. You edit the .in file and regenerate the .txt file.

You can also split development tools from runtime needs: requirements-dev.txt can start with -r requirements.txt and then add pytest and ruff. Production installs only the first file. Modern projects often declare dependencies in pyproject.toml instead, and use a lock file for exact versions, but the idea is the same: a loose list you write and an exact list a tool generates.

CompareLoose list vs pinned lock
requirements.in (you write)
  • Only direct dependencies
  • Loose ranges like >=2.31
  • Short and readable
  • Edited by hand
requirements.txt (generated)
  • Every package, direct and indirect
  • Exact == versions
  • Same install every time
  • Regenerated by a tool

Common errors and their fixes

error: externally-managed-environment. Recent Debian, Ubuntu and Homebrew Pythons refuse pip installs into the system Python (PEP 668), so that pip cannot break OS tools. The fix is exactly what this topic teaches: create a venv and install there. For command-line tools you want globally, use pipx.

ModuleNotFoundError after a successful install. The package went into a different Python than the one running your code. Check with python -m pip --version, which prints the Python it belongs to, and which python (where python on Windows). Always use python -m pip so pip matches python.

On Windows PowerShell, running .venv\Scripts\Activate.ps1 may fail because scripts are disabled. Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or use the activate.bat script from cmd.

In VS Code, choose the interpreter inside .venv (Python: Select Interpreter), or the editor will show import errors even when the terminal works.

  • python -m pip --version shows which Python pip installs into
  • pipx install ruff installs a CLI tool in its own isolated venv
  • Deleting and recreating .venv fixes most strange states

Faster tools: uv and friends

pip and venv are built in and work everywhere, so learn them first. In real teams you will also meet newer tools. uv, written in Rust, is a very fast drop-in for many pip and venv tasks: uv venv creates an environment, uv pip install -r requirements.txt installs into it, and uv pip compile turns a requirements.in into a pinned file. uv can also manage Python versions and whole projects with a pyproject.toml and a uv.lock file.

Poetry and PDM are other project managers built around pyproject.toml and lock files. Conda manages environments that include non-Python libraries, which is popular in data science.

All of them solve the same three problems this topic covers: isolate each project, record the dependencies, and recreate the same environment anywhere. If you understand venv and requirements.txt, switching tools later is easy.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Create and activate a venv~30m
  2. 2
    Install packages with pip~30m
  3. 3
    Freeze dependencies to requirements.txt~30m
  4. 4
    Recreate an environment from requirements~30m

Key points

  • One venv per project keeps package versions from clashing.
  • Your prompt shows (.venv) when the environment is active.
  • python -m pip install ensures pip matches the active Python.
  • Commit requirements.txt, but add .venv/ to .gitignore.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
python -m pip install requests
python -m pip freeze > requirements.txt
deactivate

# on another machine
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt

Two projects needing different versions

An old project needs Django 4.2, a new one needs Django 5.x. Step 1: in each project folder, create its own .venv. Step 2: activate the first and install django<5; activate the second and install django>=5. Step 3: check with python -m pip show django in each; they report different versions. Step 4: freeze each into its own requirements.txt. Neither project can break the other now.

bash
cd ~/old-site
python -m venv .venv && source .venv/bin/activate
python -m pip install "django>=4.2,<5"
python -m pip freeze > requirements.txt
deactivate

cd ~/new-site
python -m venv .venv && source .venv/bin/activate
python -m pip install "django>=5"
python -m django --version

Running a venv script from cron without activating

You have a report script that needs requests, installed in /opt/report/.venv. Cron jobs do not read your shell setup, so source activate is awkward there. Step 1: remember that activation only changes PATH. Step 2: call the venv's python by its full path; it uses the venv's packages automatically. Step 3: write output to a log so you can see errors. Step 4: test the exact command in a fresh shell before adding it to crontab.

bash
# test it first, with no venv active
/opt/report/.venv/bin/python /opt/report/report.py

# crontab -e : run every day at 07:30
30 7 * * * /opt/report/.venv/bin/python /opt/report/report.py >> /var/log/report.log 2>&1

Quick reference

  • python -m venv .venv creates it; source .venv/bin/activate (Windows: .venv\Scripts\activate)
  • Always python -m pip install ... so pip matches the active python
  • ==2.32.3 exact; >=2.31,<3 range; ~=2.32.0 means >=2.32.0 and <2.33
  • pip freeze > requirements.txt pins everything; pip install -r requirements.txt restores it
  • Add .venv/ to .gitignore; commit requirements.txt
  • externally-managed-environment error: use a venv, or pipx for global CLI tools
  • No activation needed: .venv/bin/python script.py uses the venv's packages

Common mistakes

  • Installing packages globally, then wondering why another project broke.
  • Forgetting to activate the venv, so pip installs to the wrong Python.
  • Committing the .venv folder to Git.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does activating a venv mainly do?

Question 2

2You pip installed requests, but python app.py says ModuleNotFoundError. What is the most likely cause?

Question 3

3Which specifier allows any 2.x version from 2.31 up but never 3.0?

Question 4

4Why should .venv not be committed to Git?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a venv, activate it, install requests, and prove that python and pip both come from the venv.

  2. Exercise 2medium

    Freeze your environment, delete the venv completely, recreate it from requirements.txt, and confirm the versions match.

  3. Exercise 3hard

    Set up requirements.in with only requests and rich (loose ranges), generate a fully pinned requirements.txt with pip-tools, and add a requirements-dev.txt that includes it plus pytest.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I name it .venv or venv?
Either works. .venv is a common convention that editors like VS Code detect automatically, and the leading dot hides it in many file listings.
Do I need a new venv for every script?
One per project is the norm. For tiny scripts that only use the standard library, you do not need one at all.
What is the difference between pip and pipx?
pip installs libraries into the current environment. pipx installs a command-line application into its own hidden venv and puts its command on your PATH, so tools like ruff or httpie do not clash with your projects.
How do I use a different Python version in a venv?
Create the venv with that interpreter, for example python3.12 -m venv .venv, or py -3.12 -m venv .venv on Windows. A venv always uses the Python that created it.

Go deeper

ShareXLinkedInWhatsApp