Modules

Virtual Environments

Virtual environments isolate a project's Python packages.

The standard project setup command is python -m venv .venv. It creates a directory with its own interpreter entry points and package install location. After activation, python -m pip install ... installs into that environment rather than into another project. (This workflow is for standard Python projects. The Python By Example runner is deployed from declared dependencies instead of an activated shell environment.)

Standard Python

import subprocess
import sys

subprocess.run([sys.executable, "-m", "venv", ".venv"], check=True)
subprocess.run([".venv/bin/python", "-m", "pip", "install", "requests"], check=True)
PROJECTcoderequirementsVENVpythonsite-packages
A venv carries its own interpreter and site-packages, isolating a project's dependencies from the system.

venv.EnvBuilder exposes the same environment-creation mechanism as python -m venv. A temporary directory keeps the example from leaving project files behind.

Source

import pathlib
import tempfile
import venv

with tempfile.TemporaryDirectory() as directory:
    env_path = pathlib.Path(directory) / ".venv"
    builder = venv.EnvBuilder(with_pip=False)
    builder.create(env_path)

    config = (env_path / "pyvenv.cfg").read_text()
    print(env_path.name)
    print("home" in config)

Output

.venv
True

Notes

See also

Run the complete example

Example code

Expected output

.venv
True

Execution time appears here after you run the example.