GGistDev

Virtual Environments in Python

Virtual environments isolate project dependencies from the system Python.

Creating and activating

Use the built-in venv module.

python -m venv .venv
# activate
source .venv/bin/activate      # macOS/Linux
.venv\Scripts\activate         # Windows PowerShell: .venv\Scripts\Activate.ps1

Deactivate with deactivate.

Using the environment

Install packages locally to the environment.

pip install requests
pip list

Pin dependencies with pip freeze > requirements.txt and recreate with pip install -r requirements.txt.

Selecting interpreters

Editors/IDEs can select the venv interpreter (.venv/bin/python). Use python -m pip to ensure you target the right environment.

Multiple environments

Create separate environments per project; name with .venv for conventional tooling support.

Tools and alternatives

  • pipx for isolated CLI tools
  • virtualenv (faster env creation)
  • conda for Python + native libs/data science stacks
  • poetry/pipenv for dependency management and virtualenvs

CI and deployment

Use venv to replicate production dependencies; cache pip downloads between builds.

Summary

  • Use python -m venv .venv per project, activate, then pip install
  • Pin and reproduce via requirements.txt; consider higher-level tools as needed