Python venv — Create, Check, and Use a Virtual Environment
Two projects on one machine often need two versions of the same package, and the system Python belongs to the operating system as much as to you. A virtual environment gives a project its own interpreter copy and its own package folder, so installs for one project stay out of every other project and out of the system. This guide builds an environment with the standard library venv module, reads the record it writes, checks an interpreter from inside and outside, and follows a package into the folder where it lands. Each step is a small working program with the exact output it prints.
Written November 13, 2026 · Tested with Python 3.12.3 · 13 min read
- The main program: creating an environment
- Reading pyvenv.cfg: the record of how it was made
- Telling inside from outside
- Where packages go: site-packages
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
A virtual environment is a folder that holds a Python interpreter and a private place for packages. The interpreter in the folder is a copy of, or a link to, the Python that made it, but it reads its package list from the folder, not from the system folders. The usual way to make one is a shell command, python3 -m venv .venv, run in a project folder. The programs in this guide call the same machinery through the venv module, because code can print and check each part as it goes. What the module makes is the same folder the shell command makes. On Windows the folder holds a Scripts folder instead of bin, and the activation script names differ; the layout and the checks below are the Linux ones, and the ideas carry over.
The main program: creating an environment
The create function of the venv module builds the folder. Its with_pip argument asks for the pip installer to be placed inside as well. The folder holds a bin folder with the interpreter and the activation scripts, and a file named pyvenv.cfg at the top:
import venv
from pathlib import Path
env = Path("demo-env")
venv.create(env, with_pip=True)
print((env / "bin").name)
print((env / "bin" / "python").exists())
print((env / "bin" / "activate").exists())
print((env / "pyvenv.cfg").exists())
print(sorted(path.name for path in (env / "bin").iterdir()))
The exact output:
bin
True
True
True
['Activate.ps1', 'activate', 'activate.csh', 'activate.fish', 'pip', 'pip3', 'pip3.12', 'python', 'python3', 'python3.12']
The bin folder holds three interpreter names that all start the same Python, one activation script per shell, and three pip names that all run the same installer. Activation is a convenience for shell work: running source demo-env/bin/activate in a shell puts the environment first on the path, so the plain names python and pip point into the folder until deactivate runs. Nothing about the environment needs activation to work. Calling the folder's python by its full path has the same effect, which is what the rest of this guide does.
Reading pyvenv.cfg: the record of how it was made
The pyvenv.cfg file at the top of the folder is a small key and value record. The interpreter reads it at startup to learn that it lives in an environment and where the base Python sits. This program parses the file into a dictionary and prints the keys, the system-site-packages setting, the version that made the environment, and the name of the base interpreter file:
import venv
from pathlib import Path
env = Path("demo-env")
venv.create(env, with_pip=True)
settings = {}
for line in (env / "pyvenv.cfg").read_text().splitlines():
key, _, value = line.partition(" = ")
settings[key] = value
print(sorted(settings))
print(settings["include-system-site-packages"])
print(settings["version"])
print(Path(settings["executable"]).name)
The exact output:
['command', 'executable', 'home', 'include-system-site-packages', 'version']
false
3.12.3
python3.12
The home key holds the folder of the base interpreter, and the command key holds the full command line that created the environment, paths and all. That command line is one reason an environment folder is tied to the place and the Python that made it, a point the traps section returns to. The version key is the version of the creating Python, which is the version the environment will always run: an environment does not upgrade its Python when the system Python moves on. A new Python version means a new environment, built again and filled again from a requirements list.
Telling inside from outside
Code can ask which world it is running in. The sys module holds prefix, the root the running interpreter reads its packages from, and base_prefix, the root of the Python that made the environment. Outside an environment the two are equal. Inside one, prefix points at the environment folder and the two differ. An old marker named real_prefix belongs to an older tool and does not appear in a venv environment. This program prints the outside answers, then runs the environment's own python on a short check and prints its answers:
import subprocess, sys, venv
from pathlib import Path
print(sys.prefix == sys.base_prefix)
print(hasattr(sys, "real_prefix"))
env = Path("demo-env")
venv.create(env, with_pip=False)
code = (
"import sys\n"
"from pathlib import Path\n"
"print(sys.prefix == sys.base_prefix)\n"
"print(Path(sys.executable).name)\n"
"print(sys.version_info[:2])\n"
"print(Path(sys.prefix).name)\n"
)
result = subprocess.run([str(env / "bin" / "python"), "-c", code], capture_output=True, text=True)
print(result.stdout, end="")
The exact output:
True
False
False
python
(3, 12)
demo-env
The first two lines are the outside answers: prefix and base_prefix match, and there is no real_prefix. The next four lines are the inside answers: the two prefixes differ, the interpreter file is named python, its version is 3.12, and its prefix ends with the environment folder name. Shell prompts and activation scripts show the folder name as a hint, but the prefix test is the one code can trust, and installers and test tools use it to decide where a package belongs.
Where packages go: site-packages
Packages installed into an environment land in one folder, named site-packages, under a lib folder named for the Python version. This program finds that folder with a glob, prints its name and its parent name, writes a one-line module into it the way an install would, and asks the environment's python to import the module. The system python then tries the same import:
import subprocess, sys, venv
from pathlib import Path
env = Path("demo-env")
venv.create(env, with_pip=True)
site_packages = next(env.glob("lib/*/site-packages"))
print(site_packages.name)
print(site_packages.parent.name)
(site_packages / "greeting.py").write_text('MESSAGE = "hello from the venv"\n')
code = "import greeting\nprint(greeting.MESSAGE)\n"
inside = subprocess.run([str(env / "bin" / "python"), "-c", code], capture_output=True, text=True)
print(inside.stdout, end="")
outside = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
print(outside.returncode != 0)
The exact output:
site-packages
python3.12
hello from the venv
True
The environment's python found the module because site-packages is on its import path. The system python failed, with a nonzero exit code, because its import path holds the system folders instead. A real install does more than copy a file: pip also writes a record folder with the package name, version, and file list, which is how pip can later remove or replace the package cleanly. The shape is the same, though. To see the folder from inside a running interpreter, the sysconfig module reports it as the purelib path.
The pip that belongs to the environment
An environment made with pip carries its own copy of the installer in its bin folder. That copy installs into the environment it sits in, no matter which shell runs it, because it starts with the environment's interpreter. This program asks that pip for its version, broken into parts, and then asks it to list what is installed, in freeze format:
import subprocess, venv
from pathlib import Path
env = Path("demo-env")
venv.create(env, with_pip=True)
version = subprocess.run([str(env / "bin" / "pip"), "--version"], capture_output=True, text=True).stdout.split()
print(version[0])
print(version[1])
print(" ".join(version[-2:]))
frozen = subprocess.run([str(env / "bin" / "pip"), "list", "--format=freeze"], capture_output=True, text=True).stdout.splitlines()
print(frozen)
The exact output:
pip
24.0
(python 3.12)
['pip==24.0']
A fresh environment holds pip and nothing else, so the freeze list has one line. The freeze format, a name, two equals signs, and a version, is the format of a requirements file. Saving that list with pip freeze into a file, most often named requirements.txt, records the exact set an environment holds. A new environment on another machine reads the file with pip install -r requirements.txt and rebuilds the same set. The pip version inside an environment is the version bundled with the creating Python. It stays at that version until it is upgraded inside the environment, which is a normal first step after creating one for real work.
Keeping the system out by default
An environment can be allowed to see packages installed for the system Python. The setting is off unless it is asked for, and the pyvenv.cfg value records the choice. The create function takes it as the system_site_packages argument. This program builds three small environments without pip, reads the setting back from each file, and prints it for the default build, for a build that asks to share, and for a build that refuses sharing in plain terms:
import venv
from pathlib import Path
def flag(folder, **kwargs):
env = Path(folder)
venv.create(env, with_pip=False, **kwargs)
for line in (env / "pyvenv.cfg").read_text().splitlines():
if line.startswith("include-system-site-packages"):
return line.rpartition(" = ")[2]
print(flag("plain-env"))
print(flag("shared-env", system_site_packages=True))
print(flag("isolated-env", system_site_packages=False))
The exact output:
false
true
false
The default and the plain no agree: a new environment starts empty of system packages, apart from pip when it is included. Sharing has one common use, reaching a large system package that is hard to install, such as a library the operating system ships. The cost is that the environment stops being a full record of what a project needs. A package that arrives through the system never appears in the freeze list, so a rebuilt environment on another machine lacks it, and the failure shows up far from the choice that caused it.
Three traps a first user meets
import subprocess, venv
from pathlib import Path
bare = Path("bare-env")
venv.create(bare, with_pip=False)
print((bare / "bin" / "pip").exists())
first = Path("first-env")
second = Path("second-env")
venv.create(first, with_pip=True)
venv.create(second, with_pip=False)
site_packages = next(first.glob("lib/*/site-packages"))
(site_packages / "only_first.py").write_text('VALUE = "only in first"\n')
code = "import only_first\nprint(only_first.VALUE)\n"
inside = subprocess.run([str(first / "bin" / "python"), "-c", code], capture_output=True, text=True)
print(inside.stdout, end="")
outside = subprocess.run([str(second / "bin" / "python"), "-c", code], capture_output=True, text=True)
print(outside.returncode)
old = Path("old-name")
venv.create(old, with_pip=True)
new = Path("new-name")
old.rename(new)
moved = subprocess.run([str(new / "bin" / "python"), "-c", "import sys\nfrom pathlib import Path\nprint(Path(sys.prefix).name)\n"], capture_output=True, text=True)
print(moved.stdout, end="")
try:
subprocess.run([str(new / "bin" / "pip"), "--version"], capture_output=True, text=True)
except OSError as error:
print(type(error).__name__)
The exact output:
False
only in first
1
new-name
FileNotFoundError
The bare environment reported no pip file. The module printed its value under the first environment and the same code exited with code 1 under the second. The renamed environment's python reported the new folder name as its prefix, while its pip could not be started at all: the run raised FileNotFoundError, because the interpreter named in the pip script's first line no longer exists. The fix for a moved environment is not a repair. Delete the folder, build a fresh environment at the final path, and refill it from the requirements file.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| A project with its own packages | One environment per project, with pip | Installs land in the project folder and stay out of other work |
| Running code that needs nothing new | An environment without pip | The folder is smaller and there is no installer to misuse |
| Reaching a large system library | system_site_packages turned on, noted in the project notes | The environment can import the system package, at the cost of a freeze list that no longer tells the whole story |
| Moving a project to another machine | A requirements file, not the environment folder | The folder holds paths from the machine that made it; the file rebuilds the set anywhere |
| Checking where code is running | Compare sys.prefix with sys.base_prefix | The test works in code, in any shell, with or without activation |
| Trying a tool once without touching a project | A throwaway environment in a scratch folder | The tool and its packages vanish with the folder |
Checklist
- Before installing anything, run the environment's own pip by its full path, or activate the environment and check that the prompt shows its name.
- Before trusting a freeze list, check the pyvenv.cfg setting for system site packages; a shared setting means the list is partial.
- Before moving or renaming a project folder that holds an environment, plan to delete and rebuild the environment at the new path.
- Before deleting an environment, save its freeze list if there is any chance of rebuilding it.
- Before reporting a missing package, check which interpreter ran the code; an import that works in one environment says nothing about another.
- Before creating an environment for a new Python version, remember the old one keeps its version; build a fresh folder for the new interpreter.
Related guides on this site
- Python Modules and Packages — import, Aliases, and name — how imports find modules, which is the path an environment's site-packages folder joins.
- Python pathlib — Joining Paths, Parts, Glob, and Files — the path tools this guide uses to read an environment's layout.
- Migrating to a uv Workspace: The Traps, in the Order They Bite — a newer environment and package tool, and the points where its model differs from venv and pip.
- Python argparse — Arguments, Options, and Subcommands — the command-line parsing a tool installed into an environment often grows next.
Sources
- Python Standard Library, venv — the venv module, the create function and its arguments, the folder layout, pyvenv.cfg, and how an interpreter tells it is running in an environment.
- Python Tutorial, Virtual Environments and Packages — the shell workflow of creating and activating an environment, installing packages with pip, and saving a requirements file with pip freeze.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.