Python Virtual Environments
In this page:
What is a Virtual Environment?
A virtual environment is a self-contained copy of the Python interpreter and its own package directory, letting one project depend on Django 3 while another on the same machine depends on Django 5 without either installation interfering with the other. sys.prefix points at the currently active environment's root directory.
Example: What is a Virtual Environment?
import sys
print(sys.prefix)
Detecting Active Environment
When a virtual environment is active, your shell's PATH is temporarily modified so python and pip resolve to the environment's own copies rather than the system-wide install -- you can confirm which one is active by checking sys.executable's file path.
Example: Detecting Active Environment
import sys
print(sys.executable)
Simulating Package Isolation
Each virtual environment maintains its own independent package list, isolated from the system Python and every other environment -- inspecting sys.path from within an active environment shows it searching that environment's own site-packages directory first.
Example: Simulating Package Isolation
import sys
print(sys.path[0])
Site-Packages Path Inspection
Every package installed inside an environment physically lives in a folder called site-packages, and the built-in site module can report exactly where that folder sits on disk -- useful when you need to manually inspect or clean up installed files.
Example: Site-Packages Path Inspection
import site
print(site.getsitepackages())
Environment Configuration Check
Every virtual environment contains a small pyvenv.cfg file recording which Python version created it and where; checking for this file's existence is a reliable way to programmatically detect whether a given directory is actually a valid virtual environment.
Example: Environment Configuration Check
import os
print(os.path.exists("pyvenv.cfg"))
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: