How to handle multiple projects with Python using virtual environments
How to create and activate Python virtual environments with venv so each project keeps its dependencies isolated, on macOS, Linux and Windows.
Introduction
Python is one of the most popular programming languages nowadays. It typically is the go-to option when doing Data Science, Machine Learning, and AI development. It is also very popular for building desktop applications and games.
But what happens in the event that you have more than 1 Python project that you need to work on, or perhaps you already completed one of those projects and you're trying to build the next one with a different set of dependencies?
About virtual environments in Python
A virtual environment in Python is like a dedicated workspace for your projects. Instead of installing all your Python packages globally (which can quickly get messy), a virtual environment keeps everything your project needs, such as libraries and dependencies, isolated in its own folder.
This means you can have multiple projects on the same machine, each with its own specific versions of Python packages, without them interfering with each other. For example, one project might need Django 3.2 while another requires Django 4.0—virtual environments make this possible without conflict.
Virtual environments help you:
- Keep projects independent and organized
- Avoid version clashes between dependencies
- Make your projects easier to share and reproduce on other systems
They’re an essential tool for anyone working with Python, especially as soon as you start juggling more than one project.
How to Install and Use Virtual Environments in Python
Python comes with a built-in tool called venv that makes it easy to create virtual environments. You don’t need to install anything extra if you’re using Python 3.3 or later.
Step 1: Create a virtual environment
Open your terminal and run:
python -m venv myenv
Here, myenv is just the name of your environment. You can call it whatever makes sense for your project.
Step 2: Activate the environment
To start using the environment, you need to activate it.
- On macOS and Linux:
source myenv/bin/activate
- On Windows (Command Prompt):
myenv\Scripts\activate
Once activated, you’ll notice your terminal shows the environment name at the beginning of the prompt. This means you’re working inside the virtual environment.
Step 3: Install packages inside the environment
Now you can install packages like usual, and they’ll only live inside this environment:
pip install requests
Step 4: Deactivate when done
When you’re finished working, simply run:
deactivate
This will return your terminal to the global Python environment.
As you can see, installing and managing virtual environments in Python is pretty easy, but the benefits that come with them can help you out while managing multiple Python projects.