← Back to Python Course | Chapter 8: Modules & Packages | Lesson 5 of 6

Python Virtual Environments

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?

python
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

python
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

python
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

python
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

python
import os
print(os.path.exists("pyvenv.cfg"))
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.