1 min read

Python Venv Module

The venv module provides support for creating lightweight "virtual environments" with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages.

Creating an Environment

To create a virtual environment, decide on a directory where you want to place it, and run the venv module as a script with the directory path:

# Create an environment named 'env' or '.venv'
python -m venv .venv

Activating the Environment

Before you can start installing or using packages in your virtual environment, you’ll need to activate it.

Windows

# Command Prompt
.venv\Scripts\activate.bat

# PowerShell
.venv\Scripts\Activate.ps1

macOS and Linux

source .venv/bin/activate

Once activated, your command prompt will usually change to show the name of the environment, e.g., (.venv).

Installing Packages

When the environment is active, pip will install packages into that specific environment.

pip install requests

Deactivating

To leave the virtual environment and return to the system Python, use the deactivate command.

deactivate

programming/python/python