How to Create and Use a Python Virtual Environment

Create an isolated Python virtual environment with venv, activate it, install packages, and understand why every project should use one.

Published September 17, 2026

A virtual environment is an isolated Python installation for a single project, so its dependencies don't conflict with other projects or the system-wide Python packages.

python3 -m venv venv
source venv/bin/activate   # macOS/Linux
venv\Scripts\activate      # Windows
pip install -r requirements.txt

Steps

  1. Run python3 -m venv venv to create a new virtual environment in a folder named venv
  2. Activate it with the platform-specific activate script — your shell prompt will change to show the environment name
  3. Install packages with pip while the environment is active — they're installed only inside venv, not system-wide
  4. Run 'deactivate' to leave the virtual environment

How it works

Activating a virtual environment changes your shell's PATH so that 'python' and 'pip' point to the copies inside the venv folder instead of the system installation, isolating that project's dependencies.

Things to watch for

  • Add the venv folder to .gitignore — it should never be committed, since it can be recreated from requirements.txt on any machine
  • Tools like pipenv, poetry, and conda automate virtual environment creation alongside dependency management

FAQ

Do I need to recreate the venv on a new machine?

Yes — venv folders aren't portable across machines/OSes. Commit requirements.txt (or pyproject.toml) instead, and run pip install -r requirements.txt inside a fresh venv.

More Python articles