Python · Chapter 38 of 45
Virtual Environments
A virtual environment (`venv`) is an isolated Python installation for one project. It prevents package conflicts between projects.
Always use one — never install project packages globally.
Creating and activating
`python -m venv .venv` creates one. Activate with `source .venv/bin/activate` (Mac/Linux) or `.venv\Scripts\activate` (Windows).
Deactivate
Type `deactivate` in the terminal to leave the venv.
Example 1 (bash)
python -m venv .venv
source .venv/bin/activate
pip install requests
deactivateOutput
(env active) installs requests only in .venvCreate, activate, install, deactivate.
Example 2 (bash)
pip freeze > requirements.txt
# on another machine:
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txtReproduce the same environment elsewhere.
Key points
- Isolates project dependencies.
- `python -m venv .venv`.
- Activate before running/installing.
- Commit `requirements.txt`, not the venv folder.
💡 Note: Add `.venv/` to `.gitignore`. Never commit the virtual environment itself.
