TIL: Creating Python Virtual Environments With venv
Python projects have different dependencies. Installing everything globally creates conflicts you will discover at the worst moment. venv gives each project its own isolated space.
python3 -m venv venv
Creates a venv directory with a fresh Python installation and pip. The name venv is convention but any name works.
source venv/bin/activate
Activate the environment. Your prompt changes to show (venv). Now pip install installs into this environment, not the global one.
pip install aiohttp websockets
Inside the activated environment, packages install locally. The project gets exactly the versions it needs.
deactivate
Exit the virtual environment. The prompt returns to normal and the global Python is back in use.
Should I commit the venv directory?
No. Add venv to .gitignore. Each developer runs python3 -m venv and pip install from requirements.txt.
Does venv work with Python 2?
venv is available in Python 3.3 and later. Python 2 projects use virtualenv instead.