Modules
Virtual Environments
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)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
TrueNotes
- Use
python -m venv .venvfor everyday standard-Python project setup. - A venv isolates installed packages; it does not change how imports are written.
- This site's runner uses a deployment dependency model, not an activated shell environment.
- That runner constraint is separate from the standard Python
venvworkflow you would use in local projects.
See also
- related: Packages
- related: Modules
- related: Import Aliases
Run the complete example
Expected output
.venv
True
Execution time appears here after you run the example.