Skip to content

/commands/python/create-virtual-environment-venv

python -m venv .venv: create and activate a virtual environment

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated
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

bash
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)'
done

Output

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

ShellCommand
bash / zsh (Linux, macOS)source .venv/bin/activate
fishsource .venv/bin/activate.fish
Windows cmd.exe.venv\Scripts\activate.bat
Windows PowerShell.venv\Scripts\Activate.ps1
Git Bash on Windowssource .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

bash
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python -m pip freeze > requirements.txt
deactivate

Useful options

OptionEffect
--upgrade-depsUpgrade pip in the new environment (3.9+)
--without-pipDo not install pip
--system-site-packagesLet the environment see packages of the base Python
--prompt NAMEName shown in the shell prompt while active
--clearDelete 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.

Sources