/commands/python/create-virtual-environment-venv
python -m venv .venv: create and activate a virtual environment
- tool
- Python
- versions
- Python 3.3+
- os
- linux, macos, windows
python -m venv .venv creates a virtual environment in the .venv folder: a private Python with its own site-packages, so packages installed there do not touch the system Python. Activate it with source .venv/bin/activate on Linux and macOS, or .venv\Scripts\activate on Windows; deactivate leaves it.
Create and check it
python -m venv .venv
test -f .venv/pyvenv.cfg && echo "created .venv/pyvenv.cfg"
for p in .venv/bin/python .venv/Scripts/python.exe; do
[ -x "$p" ] && "$p" -c 'import sys; print("inside a venv:", sys.prefix != sys.base_prefix)'
doneOutput
created .venv/pyvenv.cfg inside a venv: True
sys.prefix != sys.base_prefix is the reliable way to tell whether code runs inside a virtual environment.
Activate it
| Shell | Command |
|---|---|
| bash / zsh (Linux, macOS) | source .venv/bin/activate |
| fish | source .venv/bin/activate.fish |
| Windows cmd.exe | .venv\Scripts\activate.bat |
| Windows PowerShell | .venv\Scripts\Activate.ps1 |
| Git Bash on Windows | source .venv/Scripts/activate |
Activation only prepends the environment's bin (or Scripts) folder to PATH and sets VIRTUAL_ENV. You can skip it and call the interpreter directly: .venv/bin/python -m pip install requests.
Typical workflow
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python -m pip freeze > requirements.txt
deactivateUseful options
| Option | Effect |
|---|---|
| --upgrade-deps | Upgrade pip in the new environment (3.9+) |
| --without-pip | Do not install pip |
| --system-site-packages | Let the environment see packages of the base Python |
| --prompt NAME | Name shown in the shell prompt while active |
| --clear | Delete the contents of an existing environment first |
Add .venv/ to .gitignore: an environment contains absolute paths and is not portable between machines. Recreate it from requirements.txt instead.