Sub topic 2
Creating a virtual environment with python -m venv
This chapter assumes you can run commands in a terminal, run a Python script, and import a module. It also assumes Python 3 is on your command line. You will create an environment, choose its options, and learn what can go wrong at creation time. Activation, the environment's internal layout, and installing packages have their own chapters, so here you will call the environment's interpreter by path.
What venv does
venv is a module in the Python standard library. It builds a directory that holds a private copy of, or link to, a Python interpreter, plus an empty place to install packages. Any package you install with that interpreter goes into the directory. It does not go into the shared Python installation.
The interpreter that runs the command becomes the base interpreter of the new environment. If you run python3.12 -m venv .venv, the environment uses Python 3.12. If you run it with python3.9, you get 3.9. An environment cannot change its Python version later. To use a different version, create a new environment.
The basic command
On Linux or macOS:
python3 -m venv .venv
ls .venv
.venv/bin/python -c "import sys; print(sys.prefix); print(sys.base_prefix)"On Windows, the py launcher selects a Python and the interpreter lives in Scripts:
py -m venv .venv
dir .venv
.venv\Scripts\python.exe -c "import sys; print(sys.prefix); print(sys.base_prefix)"The last line prints two paths. sys.prefix points inside .venv. sys.base_prefix points to the Python installation that created it. When the two differ, Python is running inside a virtual environment. This is the most reliable check, and later chapters use it for troubleshooting.
Why `python -m venv` and not a `venv` command
The -m flag tells Python to run a module by name. Writing python3 -m venv makes the choice of base interpreter explicit: the Python you typed is the one the environment is built from. A standalone command could pick up a different Python from your PATH without telling you. You will see the same pattern with python -m pip in later chapters, for the same reason.
Choosing a name and location
The conventional choice is a directory named .venv at the project root. Many editors and tools look for .venv automatically. The name venv is also common. Keep one environment per project, and put it inside the project directory so the pairing is obvious.
The environment's name also affects the prompt you see once you activate it. By default the prompt prefix is the directory name. For an environment named .venv, the prefix would be (.venv), which says nothing about the project. The --prompt option fixes this (see below).
Options you will actually use
| Option | Effect |
|---|---|
| `--prompt NAME` | Sets the text shown in the shell prompt when activated. `--prompt .` uses the current directory's name. |
| `--upgrade-deps` | Upgrades pip, and setuptools on Python versions before 3.12, to the latest release from the package index after creation. |
| `--without-pip` | Skips installing pip. |
| `--system-site-packages` | Lets the environment see packages installed in the base installation. |
| `--clear` | Deletes the contents of the target directory before creating the environment. |
| `--upgrade` | Updates an existing environment to point at the running Python, without touching installed packages. |
| `--copies` | Copies the interpreter instead of symlinking it. |
| `--symlinks` | Symlinks the interpreter where the platform supports it. This is the default on POSIX systems. |
A typical command for a real project:
python3 -m venv --prompt . --upgrade-deps .venvThe two options do different jobs. --prompt . labels the environment with the project folder's name. --upgrade-deps matters because the pip that ships bundled with Python can be several releases old by the time you use it.
Isolation and `--system-site-packages`
By default an environment is isolated. It does not see packages installed in the base Python's site-packages. This is the point of the tool, and it is why the default should usually stay.
With --system-site-packages, the environment can also import whatever the base installation has. This is occasionally useful when a package is hard to build and your operating system supplies it, such as some GUI or scientific bindings. The cost is that your environment now depends on the system installation, which brings back the conflicts that isolation was meant to prevent. The option sets include-system-site-packages = true in the environment's pyvenv.cfg file, which you can edit later.
Symlinks and copies
On Linux and macOS, venv symlinks the interpreter by default. This is fast and small. The environment works only while the base interpreter stays where it was, since the link points to it. On Windows, files are copied by default. Use --copies on POSIX if the base installation may move or if you build container layers that do not preserve symlinks.
Recreating and upgrading
Running the command again on an existing directory does not delete packages. It refreshes the environment's scripts and leaves your installed packages alone. Use --clear when you want a clean start:
python3 -m venv --clear .venv--clear removes everything in .venv, including installed packages. That is usually what you want when an environment is broken, because rebuilding from a requirements file is cheap.
--upgrade handles a different case. If your system Python was upgraded in place (for example, a patch release) and the environment's symlinks or pyvenv.cfg are stale, --upgrade repairs the links without reinstalling packages. It does not move an environment to a new minor version. For that, create a fresh environment.
Creating an environment from Python code
The same functionality is available as venv.create. Tools and test suites use it to build environments programmatically.
import subprocess
import sys
import venv
from pathlib import Path
env_dir = Path("demo-env")
venv.create(env_dir, with_pip=True, clear=True)
python = env_dir / ("Scripts" if sys.platform == "win32" else "bin") / "python"
result = subprocess.run(
[str(python), "-c", "import sys; print(sys.prefix != sys.base_prefix)"],
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())This prints True. Note that venv.create defaults to with_pip=False, which is the opposite of the command line. If you forget the argument in code, your environment has no pip.
Common creation problems
ensurepip is not available on Debian or Ubuntu. These distributions split the standard library. The venv module exists, but the bundled pip installer is in a separate package. Install it with the system package manager, for example sudo apt install python3-venv. Some versions name the package after the minor version, such as python3.12-venv. The error message names the exact package to install.
A half-created .venv after a failed run. The directory exists but has no working python. Run the command again with --clear to start over.
Wrong Python version. If python3 --version shows an older release than you expected, the command builds with that older release. Call the version explicitly, such as python3.12 -m venv .venv, or on Windows py -3.12 -m venv .venv.
Moving or renaming the directory. Environments store absolute paths. Scripts in bin or Scripts record the location where the environment was created. A moved environment may start but behave wrongly, such as launching entry-point scripts from the old location. Delete the environment and recreate it in the new place.
Reusing an environment on another machine. An environment is tied to the path and the interpreter of the machine that made it. Do not copy it between computers or commit it. Rebuild it from a requirements file instead. Later chapters cover that process.
Checking that the environment works
After creation, three quick checks confirm that the environment is sound, without activating it:
.venv/bin/python --version
.venv/bin/python -m pip --version
.venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"The second command should print a pip path inside .venv. The third should print True. If pip is missing, the environment was created with --without-pip, or ensurepip failed. If the third check prints False, you ran a different Python than the one in the environment.
Exercise
You run python3 -m venv .venv and later find that a colleague's copy of the project cannot use the .venv directory you zipped and sent them. Give two reasons it fails, and say what to send instead.
Show answer
The environment stores absolute paths and, on Linux and macOS, symlinks to the base interpreter on the original machine, so both are wrong on the colleague's computer. The interpreter version and operating system may also differ. Do not send the directory. Send the project with a requirements file, and have the colleague create their own environment with python3 -m venv .venv and install from that file.
Exercise
A tutorial tells you to run venv.create("env") from Python and then pip is missing from the new environment. What caused it, and how do you fix the call?
Show answer
The venv.create function defaults to with_pip=False, unlike the command line. Call venv.create("env", with_pip=True) so that ensurepip installs pip into the environment.