How do I create and manage virtual environments in Python?

· Category: Python Programming

Short answer

A virtual environment is an isolated Python installation with its own packages. Use the built-in venv module (or virtualenv) to create one, then activate it to keep project dependencies separate from the system Python.

Steps

  1. Create a virtual environment: python -m venv .venv.
  2. Activate it (Windows: .venv\Scriptsctivate, Linux/macOS: source .venv/bin/activate).
  3. Install packages with pip.
python -m venv .venv
.venv\Scriptsctivate
pip install requests

Tips

  • Always add .venv/ or venv/ to .gitignore.
  • Pin dependencies with pip freeze > requirements.txt and recreate environments with pip install -r requirements.txt.
  • virtualenv is a third-party tool with additional features; venv is built-in and sufficient for most cases.
  • Use python -m pip instead of pip directly to ensure you are using the environment's pip.

Common issues

  • Forgetting to activate the environment installs packages into the system Python.
  • Moving a virtual environment directory breaks absolute paths in scripts; recreate it instead.
  • Conflicts between globally installed packages and virtual environment packages can cause unexpected behavior.