virtualenv is a Python tool that creates isolated environments.
Each environment can have its own:
- Python version
- Packages
- Dependencies
This is extremely helpful when:
- You work on multiple Python projects
- Each project needs different library versions
- You want to avoid breaking your global Python installation
Prerequisite
- python must be installed
- pip must be installed
Check Python & pip Installation
Open your terminal (or PowerShell on Windows) and run:
Bash
python --version
pip --version
If these commands work, you’re good to continue. If not, install Python first from:Â https://www.python.org/downloads/
Install virtualenv
Run this command on Windows, macOS, or Linux:
Bash
pip install virtualenv
To confirm installation:
Bash
virtualenv --version
Using Virtualenv on Windows
Create a Virtual Environment
Bash
virtualenv venv
This creates a folder named venv/.
Activate the Environment
Bash
venv\Scripts\activate
You should now see:
Bash
(venv)
Install Packages
Bash
pip install requests flask numpy
Deactivate
Bash
deactivate
Using Virtualenv on macOS
Create a Virtual Environment
Bash
virtualenv venv
Activate
Bash
source venv/bin/activate
The terminal prompt changes to:
Bash
(venv)
Install Packages
Bash
pip install pandas django
Deactivate
Bash
deactivateUsing Virtualenv on Linux
Install virtualenv (if pip is missing)
On Ubuntu/Debian:
Bash
sudo apt update
sudo apt install python3-pip
pip3 install virtualenv
Create a Virtual Environment
Bash
virtualenv venv
Activate
Bash
source venv/bin/activate
Deactivate
Bash
deactivate
Virtualenv Best Practices
| Good Practice | Why It Matters |
|---|---|
| Create one virtual environment per project | Prevents dependency conflicts |
| Keep the venv folder inside your project | Easy to manage |
Use requirements.txt | Helps you reinstall packages quickly |
Never commit venv to Git | It is large & auto generated |
Generate requirements.txt
Bash
pip freeze > requirements.txtInstall packages from requirements.txt
Bash
pip install -r requirements.txtSummary
Always use virutalenv when creating new projects in python. It creates isolated environment for your application and your life will be easy when working with adding, updating and removing python packages