Managing dependencies in Python is critical to avoid version conflicts between projects. Virtual environments create isolated spaces where you can install specific packages without affecting your system's global Python installation.
This guide explains how to create, activate, and deactivate Python virtual environments using the built-in venv module.
Understanding Virtual Environments
A Python virtual environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
- Global Scope: Installing packages system-wide can break other projects that rely on different versions of the same library.
- Isolated Scope: A virtual environment ensures that
Project Acan userequests==2.0whileProject Busesrequests==3.0with no conflicts.
Creating a Virtual Environment
Python 3.3+ comes with the venv module standard. To create an environment, navigate to your project directory and run the following command.
mkdir -p ~/project/my_project
cd ~/project/my_project
python3 -m venv venvThis creates a folder named venv containing the isolated Python binaries and library folders (bin, lib, include).
Activating the Environment
Activation is the step that modifies your shell's environment variables to point to the isolated Python interpreter instead of the system global one. The command differs slightly depending on your operating system.
Activation Commands
For Linux and macOS:
source venv/bin/activateFor Windows (Command Prompt):
venv\Scripts\activate.batFor Windows (PowerShell):
venv\Scripts\Activate.ps1Verifying Activation
Once activated, your command prompt usually changes to show the environment name in parentheses. You can verify the path using which (Linux/Mac) or where (Windows).
which pythonIf you are not activated:
which pythonInstalling Packages Safely
Once activated, any package you install using pip is placed inside the virtual environment's lib directory.
(venv) $ pip install requestsThe Risk of Not Activating
If you forget to activate the environment, you risk polluting your global system.
$ pip install requests
$ source venv/bin/activate
(venv) $ pip install requestsDeactivating the Environment
When you are finished working on your project, you should exit the virtual environment to return to your system's default Python context.
The Deactivate Command
This command is the same across all operating systems and shells (provided the environment is currently active).
(venv) $ deactivate
$ Verifying Deactivation
After running the command, the (venv) prefix will disappear from your prompt.
which pythonConclusion
Using virtual environments is a best practice for Python development.
- Create using
python3 -m venv <name>. - Activate using
source <name>/bin/activate(Linux/Mac) or<name>\Scripts\activate(Windows). - Install packages safely with
pip. - Deactivate with
deactivatewhen finished.