Sub topic 13
Isolating a project with a virtual environment
This chapter assumes you can open a terminal, run python3 --version (or py --version on Windows), and run a script file. By the end you will create a virtual environment, activate it, confirm that Python is using it, and recreate it from a list of requirements.
Why projects need isolation
A Python installation has one place where installed packages live, called site-packages. If every project installs into that one place, three problems appear:
- Version conflicts. Project A needs
requests2.25 and project B needsrequests2.31. Only one can be installed at a time. - Hidden dependencies. A script works on your machine only because some unrelated project installed a package it needs. It fails on a clean machine.
- System damage. On Linux and macOS, system tools may depend on the system Python. Changing its packages can break them. Many Linux distributions now refuse global
pip installfor this reason and print an "externally-managed-environment" error.
A virtual environment is a folder that holds its own copy of (or link to) the interpreter and its own site-packages. Installing a package while the environment is active changes only that folder. The base Python installation stays untouched.
What `venv` creates
The venv module ships with Python. This command creates an environment in a folder named .venv:
python3 -m venv .venv
# On Windows, use: py -m venv .venvThe command takes a moment to run and prints nothing when it succeeds. The -m venv part tells Python to run the venv module as a program. The final argument is the folder to create. .venv is a common name because many editors and tools look for it automatically. venv and env are also in use.
The folder has this structure:
| Item | Windows | macOS and Linux | Purpose |
|---|---|---|---|
| Executables | `Scripts\` | `bin/` | `python`, `pip`, and the activation scripts |
| Packages | `Lib\site-packages\` | `lib/python3.X/site-packages/` | Where installed packages go |
| `pyvenv.cfg` | yes | yes | Records which base Python created the environment |
The python executable inside the environment is a symlink or small copy that points back to the base interpreter. When it starts, Python reads pyvenv.cfg in the parent folder. It then puts the environment's site-packages on its search path instead of the global one.
Activating the environment
Creating the environment does not use it. You activate it so that python and pip in your current terminal refer to the environment's copies. The command depends on your shell:
# macOS and Linux (bash, zsh)
source .venv/bin/activate
# Windows, Command Prompt
.venv\Scripts\activate.bat
# Windows, PowerShell
.venv\Scripts\Activate.ps1After activation your prompt gains a prefix such as (.venv). Activation does only two things. It puts the environment's bin (or Scripts) folder at the front of your PATH, and it sets a VIRTUAL_ENV variable. That is why the python command now finds the environment's interpreter first.
To leave the environment, run:
deactivateThis works in every shell, restores your PATH, and removes the prompt prefix. Activation lasts only for the current terminal window. A new window starts without it.
Confirming that you are inside the environment
Do not rely only on the prompt prefix. Check what Python itself reports. Save this as where_am_i.py:
import sys
print("executable :", sys.executable)
print("prefix :", sys.prefix)
print("base_prefix:", sys.base_prefix)
print("in a venv :", sys.prefix != sys.base_prefix)Run it with python where_am_i.py while the environment is active. Inside a virtual environment, sys.prefix points to your .venv folder and sys.base_prefix points to the Python installation that created it. The last line prints True. Outside an environment, the two values are equal and the last line prints False.
You can also ask the shell which executable it will run:
# macOS and Linux
which python
# Windows, Command Prompt
where pythonThe first result should be inside your .venv folder.
Installing into the environment
With the environment active, install packages with pip. Run it as python -m pip rather than bare pip. That form guarantees pip belongs to the same interpreter that python runs.
python -m pip install requests
python -m pip listThe list shows only pip and the packages you installed. A fresh environment does not inherit packages from the global installation. If you deactivate and run python -m pip list again, requests is missing from the global list. That absence is the isolation working.
Running without activating
Activation is a convenience, not a requirement. You can call the environment's interpreter by its path:
.venv/bin/python hello.py
# On Windows: .venv\Scripts\python.exe hello.pyThis is useful in scheduled jobs, editor run configurations, and scripts, where no one has activated anything first. The packages in .venv are available because the interpreter reads its own pyvenv.cfg.
Recording and recreating the environment
An environment is disposable. Do not copy it to another machine or commit it to version control. Instead, record what it contains and rebuild it on demand.
python -m pip freeze > requirements.txtpip freeze prints every installed package with its exact version, one per line. The redirect > saves that output to requirements.txt. On another machine, or after deleting the environment, rebuild it:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txtOn Windows, use py -m venv .venv and the activation command from the earlier section. Commit requirements.txt to version control, and add .venv/ to .gitignore. Python 3.13 and later write a .gitignore inside the .venv folder for you. On older versions, add the line yourself.
Note that pip freeze also lists packages that your packages depend on. That is acceptable for a first project. Larger projects often keep a short hand-written list of direct dependencies and use a lock tool. That is beyond this chapter.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ensurepip is not available` or "The virtual environment was not created successfully" on Debian or Ubuntu | The distribution splits `venv` support into a separate package | `sudo apt install python3-venv`, then delete the half-made `.venv` and retry |
| `No such file or directory: .venv/bin/activate` | You are in the wrong folder, or the environment was never created | Run `ls` (or `dir`) to check your location, then create it |
| Packages are missing after activating | A different terminal window, or activation did not happen | Check `which python` or `where python`, and look for the `(.venv)` prefix |
| `pip install` changes the global Python | The environment was not active | Run `deactivate` if needed, activate the right one, and reinstall |
| Environment stops working after you move or rename its folder | Scripts and `pyvenv.cfg` contain absolute paths | Delete the folder and recreate it from `requirements.txt` |
| Environment breaks after upgrading Python | The link to the old base interpreter is gone | Recreate it, or run `python3 -m venv --upgrade .venv` |
Limits of `venv`
A virtual environment isolates Python packages only. It does not isolate the Python version itself, because the environment uses whichever interpreter created it. To work with a different Python version, create the environment with that version's launcher, for example python3.12 -m venv .venv or py -3.12 -m venv .venv. It also does not isolate system libraries, databases, or other programs. Tools such as containers handle those cases.
Exercise
You activate .venv, run python -m pip install requests, and then open a second terminal window and run python -c "import requests". It fails with ModuleNotFoundError. Give two possible reasons, and say how you would check which one applies.
Show answer
Either the second window never activated .venv, so python is the global interpreter that has no requests. Or the second window activated a different environment. Check with which python (macOS and Linux) or where python (Windows). If the path is not inside the project's .venv, activate it with the activation command for your shell and try again. You can also run python -c "import sys; print(sys.prefix != sys.base_prefix)", which prints False outside an environment.
Exercise
A teammate sends you a project folder that includes a .venv directory they created on their computer, and it does not work on yours. Why, and what should they have shared instead?
Show answer
The environment contains absolute paths and links to an interpreter installed on their machine, and the executables may be built for a different operating system. They should have shared requirements.txt, created with python -m pip freeze > requirements.txt. You then create your own .venv and run python -m pip install -r requirements.txt.