Virtual Environments β venv#
A virtual environment gives each project its own isolated Python installation. Never install packages into the system Python.
Create a virtual environment#
python -m venv .venv
Output:
(no output β the .venv/ directory is created)
The conventional name is .venv or venv. Use .venv so editors (VS Code, PyCharm) auto-detect it.
Activate#
Activation makes .venv/bin/python and .venv/bin/pip the active interpreter.
# bash / zsh
source .venv/bin/activate
# fish
source .venv/bin/activate.fish
# Windows PowerShell
.venv\Scripts\Activate.ps1
# Windows cmd.exe
.venv\Scripts\activate.bat
After activation your shell prompt changes to show the environment name:
Output:
(.venv) user@host:~/myproject $
Check youβre in the right environment:
which python
Output:
/home/user/myproject/.venv/bin/python
Install packages#
pip install requests pandas
pip install "fastapi>=0.111" "pydantic>=2" # version constraints
Output:
Collecting requests
Downloading requests-2.32.3-py3-none-any.whl (64 kB)
Collecting pandas
Downloading pandas-2.2.2-cp312-cp312-manylinux_2_17_x86_64.whl (13.0 MB)
Successfully installed certifi-2024.2.2 requests-2.32.3 pandas-2.2.2 ...
Freeze / requirements#
# Save exact versions of all installed packages
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txt
Output of pip freeze:
certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.7
pandas==2.2.2
python-dateutil==2.9.0
requests==2.32.3
[!TIP]
pip freezeincludes all transitive dependencies. For authoring a library or apyproject.toml-based project, prefer poetry or uv which maintain a separate lockfile.
Deactivate#
deactivate
Output:
(prompt returns to normal β no (.venv) prefix)
Upgrade pip inside the venv#
pip install --upgrade pip
Output:
Requirement already satisfied: pip in ./.venv/lib/python3.12/site-packages (24.0)
Successfully installed pip-24.3.1
Delete and recreate#
rm -rf .venv
python -m venv .venv
There are no lock files or metadata to clean up β just remove and recreate.
Quick reference table#
| Task | Command |
|---|---|
| Create | python -m venv .venv |
| Activate (bash/zsh) | source .venv/bin/activate |
| Activate (fish) | source .venv/bin/activate.fish |
| Activate (PowerShell) | .venv\Scripts\Activate.ps1 |
| Install package | pip install <pkg> |
| List installed | pip list |
| Freeze to file | pip freeze > requirements.txt |
| Install from file | pip install -r requirements.txt |
| Deactivate | deactivate |
| Delete | rm -rf .venv |
Common pitfalls#
[!WARNING] Running without activation β if you
python script.pywithout activating, youβll use the system Python and wonβt see your installed packages. Checkwhich pythonbefore running anything.
[!WARNING] PowerShell execution policy β if
.venv\Scripts\Activate.ps1fails with a policy error, run:Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
[!TIP] Add
.venv/to your.gitignore. Never commit the virtual environment directory.