A virtual environment is a private folder of Python packages for one project. Without one, every project on your computer shares the same packages, so upgrading a library for one project can break another. With one, each project has exactly the versions it needs, and you can delete the folder and start again any time.
Python has the venv module built in, so there's nothing to install.
Create one
Open a terminal in your project folder and run:
# Windows
py -m venv .venv
# macOS and Linux
python3 -m venv .venv
That makes a folder called .venv containing a link to (or, on Windows, a copy of) Python and its own site-packages folder. The name is up to you, but .venv is the usual choice, and many editors spot it automatically. From Python 3.13, venv also puts a .gitignore file inside the folder so Git ignores it.
Activate it
| System | Command |
|---|---|
| Windows, Command Prompt | .venv\Scripts\activate.bat |
| Windows, PowerShell | .venv\Scripts\Activate.ps1 |
| macOS or Linux, bash or zsh | source .venv/bin/activate |
Once it's active, your prompt usually shows (.venv) at the start, and python and pip now mean the environment's copies. Check with:
python -c "import sys; print(sys.prefix != sys.base_prefix)"
True
True means you're inside a virtual environment.
"Running scripts is disabled on this system"
PowerShell blocks scripts by default on some Windows setups. The Python documentation's fix is to allow locally created scripts for your user account:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Or use Command Prompt and activate.bat instead.
Install packages
pip install requests
With the environment active, that installs into .venv only. If you're ever unsure which pip you're using, python -m pip install requests always installs for the Python you're running.
Save and restore your packages
Write the exact versions you're using to a file you can share or commit:
pip freeze > requirements.txt
On another computer, or after deleting .venv, make a fresh environment, activate it and reinstall everything:
pip install -r requirements.txt
Leave it
deactivate
Good habits
- Don't commit
.venvto Git. Commitrequirements.txtinstead. If your Python is older than 3.13, add.venv/to your project's.gitignoreyourself. - Don't move or rename the folder. It contains paths to where it was created. If you move the project, delete
.venvand create a new one. - One environment per project. They're cheap to make and quick to delete.
- Pick the interpreter in your editor. In VS Code, use "Python: Select Interpreter" and choose the one inside
.venv. - On a Raspberry Pi, Raspberry Pi OS stops pip installing into the system Python, so a virtual environment is the normal way to install packages. If you need the system's pre-installed libraries such as
gpiozerotoo, create it withpython3 -m venv --system-site-packages .venv.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.