Part 07 / Topic 7 of 9
Virtual environments (venv)
A virtual environment (venv) is a private folder of packages for one project. Think of it as a separate lunch box per project: nothing mixes. Project A can use requests 2.31 while project B uses requests 2.32, with no clash. Always make one per project.
Real-world example: start a new "weather app" project.
cd weather-app # go into the project folder (cd = change folder, see Part 1)
python -m venv .venv # create a venv in a folder named .venv
On macOS / Linux use python3 if python is not found. On Windows, py -m venv .venv also works.
Activate it, so python and pip now mean the venv's copies. Run this from the project folder:
| System | Command |
|---|---|
| Windows (Command Prompt) | .venv\Scripts\activate.bat |
| Windows (PowerShell) | .venv\Scripts\Activate.ps1 |
| Windows (Git Bash) | source .venv/Scripts/activate |
| macOS / Linux (bash, zsh) | source .venv/bin/activate |
Your prompt then starts with (.venv):
(.venv) $ python --version # now uses the venv's Python
(.venv) $ deactivate # leave the venv (same command on every system)
- Add
.venv/to.gitignore. Never commit it. Sharerequirements.txtinstead. - If PowerShell says "running scripts is disabled", run this once, then try again:
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.
๐ Going deeper: a venv is just a folder with its own
python, its ownsite-packages, and a smallpyvenv.cfgtext file. On macOS / Linux.venv/bin/pythonis a link to the real interpreter; on Windows.venv\Scripts\python.exeis a small copy (a redirector) that starts the real one. When thatpythonstarts, it findspyvenv.cfgnext to it (or one folder up), so it knows it is inside a venv: it setssys.prefixto the venv folder and uses the venv'ssite-packages(check withimport sys; print(sys.prefix)). "Activating" does not change Python at all. It only puts.venv/bin(Windows:.venv\Scripts) first on yourPATH, sets theVIRTUAL_ENVenvironment variable, and adds(.venv)to your prompt. So you can skip activation and call.venv/bin/python(Windows:.venv\Scripts\python) directly, which is what editors and scripts usually do.
Read more: the official venv documentation.
Done here? The practice set for Part 7 โ 7 exercises with solutions โ is on the part page.