Browse topics

Virtual environments with venv

Version
3.14
Since
3.3
Review
Draft

Summary#

venv creates a directory with its own interpreter entry point and installed packages on top of an existing Python installation. Activation is optional because you can run the environment's interpreter by its path.

Syntax#

sh
python -m venv .venv
source .venv/bin/activate      # bash or zsh
deactivate
.venv/bin/python -m pip list   # no activation needed
# Windows cmd.exe activation: .venv\Scripts\activate.bat

Example#

python
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    env_dir = Path(directory) / ".venv"
    subprocess.run(
        [sys.executable, "-m", "venv", "--without-pip", env_dir], check=True
    )

    windows = sys.platform == "win32"
    python = env_dir / ("Scripts/python.exe" if windows else "bin/python")
    probe = "import sys; print(sys.prefix != sys.base_prefix)"
    result = subprocess.run(
        [python, "-I", "-c", probe], check=True, capture_output=True, text=True
    )

    print((env_dir / "pyvenv.cfg").is_file())
    print(result.stdout.strip())

Expected output#

Text
True
True

Common mistakes#

Do not move or copy an environment to another location. Installed scripts refer to its interpreter by absolute path, so recreate it and reinstall the requirements. Keep project code and the environment directory separate, and leave the environment out of version control. The VIRTUAL_ENV variable is not a reliable test because activation is optional.

Version applicability#

venv was added in Python 3.3. Installing pip by default and --without-pip require Python 3.4 or later. The example needs 3.7 on POSIX for capture_output and text, and 3.8 on Windows for Path arguments to subprocess.run. Since Python 3.12, setuptools is no longer a core dependency installed into new environments.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0