Python Virtual Environments in Depth
A venv is a folder that holds one Python environment. The environment has its own set of packages.
Create a venv (shell)
This is a shell transcript, not Python. One command builds the whole folder.
$ python3 -m venv demo-venvLook inside the folder (shell)
The new folder holds a few standard parts. pyvenv.cfg is the pointer file.
$ ls demo-venvActivate on macOS or Linux (shell)
Activation points your shell at the venv's Python. The prompt shows the venv's name.
$ source demo-venv/bin/activate
(demo-venv) $Activate on Windows (shell)
Windows keeps its scripts in a Scripts folder instead of bin. PowerShell users run Activate.ps1 from that same folder.
demo-venv\Scripts\activateProve which Python is running
Run this with the venv active. sys.prefix names the folder Python treats as home.
import sys
print(sys.prefix == sys.base_prefix)Example
import sys
from pathlib import Path
print("Inside a venv:", sys.prefix != sys.base_prefix)
print("Venv folder:", Path(sys.prefix).name)
print("Python program:", Path(sys.executable).name)Key points
- Environment: one Python setup with its own set of packages, kept apart from the others
- A venv is a folder.
- A small file inside it, pyvenv.cfg, points back to the base Python
- Base Python: the real Python on your machine, the one the venv borrows
- Use python3 -m venv NAME to create a venv in a new folder
- Use deactivate to leave a venv and return to the base Python
- Delete the folder to remove the venv.
- Nothing was installed anywhere else
In this example, the program runs with the venv's Python. sys.prefix is the venv folder. sys.base_prefix is the base Python's folder. The two differ, so the first line prints True. Path(sys.prefix).name gives just the folder's name, demo-venv. sys.executable is the Python program that is running. Its name is python, the one inside the venv's bin folder. Run the same file with your normal python3 and the first line prints False.
Note
A venv does not copy the whole Python.
It borrows the base Python and only adds its own packages on top.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
You delete the demo-venv folder. What happens to the base Python on your machine?