When you're working with Python, it's a best practice to isolate your project’s dependencies using a virtual environment. This helps avoid version conflicts and keeps your global Python setup clean. In this guide, we’ll walk you through how to create and manage a Python virtual environment using virtualenv on both Linux and Windows Subsystem for Linux (WSL2).
What Is a Virtual Environment?
A virtual environment is like a sandbox—it lets you install Python packages in an isolated workspace, so they don’t interfere with other projects or the system Python.While Python 3 has a built-in module called venv, virtualenv is more flexible, faster, and works with older Python versions. It’s a popular choice for many developers. Let's create virtual environement with virtualenv in the step by step manner.
Step 1: Install Python (if not already installed)
Check if Python is installed:
python3 --version
If it’s not, install it:
For Ubuntu/Linux/WSL2:
sudo apt update
sudo apt install python3 python3-pip -y
Step 2: Install virtualenv
Use pip to install virtualenv globally:
sudo apt install python3-virtualenv
Check if it’s installed:
virtualenv --version
Step 3: Create a Virtual Environment
Navigate to your project folder (or create one):
mkdir my_project
cd my_project
Create the virtual environment:
virtualenv venv
Here, venv is the name of your virtual environment folder (you can name it anything you like).
Step 4: Activate the Virtual Environment
On Linux or WSL2:
source venv/bin/activate
Once activated, your shell will show the environment name, like:
(venv) user@hostname:~/my_project$
Now you're working inside the virtual environment.
Step 5: Install Packages Inside the Environment
Now you can install packages without affecting your global Python:
pip install flask
Step 6: Deactivate the Environment
When you’re done, deactivate it with:
deactivate
You’re now back to your system’s Python.
Extra Tips
Use requirements.txt to save dependencies:
pip freeze > requirements.txt
Install them in another setup using:
pip install -r requirements.txt
Delete the venv folder to remove the environment completely. Using virtualenv is a simple but powerful way to manage your Python projects, especially on Linux or WSL2. It helps keep your environment clean, organized, and consistent across different machines.If you're just starting out with Python development, this is one of the best habits you can build early on.