- Published on
Virtual environments in Python
- Authors
- Name
- Cristian Pique
Introduction
Virtual environments in Python are a powerful tool for managing dependencies and isolating different projects. They allow developers to create isolated environments for their Python projects, each with its own set of installed packages and dependencies. This is particularly useful when working on multiple projects that require different versions of the same package, or when you don't want to pollute your system's global Python environment with packages you're only using for a specific project.
The latest version of Python, currently 3.10, includes built-in support for virtual environments through the venv module. This module allows you to easily create and manage virtual environments from the command line.
To create a new virtual environment, you can use the python -m venv
command, followed by the name of the environment you want to create. For example, to create a virtual environment called "myenv", you would run the following command:
python -m venv myenv
Once the environment has been created, you can activate it by running the appropriate script located in the environment's bin folder (activate or activate.bat)
.\Scripts\activate
The code above is to execute the activate
script.
If you use Linux
, you can use this command:
source myenv/bin/activate
Examples were created using Windows. If you use Linux, commands may vary slightly
You can also deactivate an active environment with the command deactivate
.
When you activate a virtual environment, the packages you install with pip will be installed inside that environment, rather than in your system's global Python environment. This allows you to keep your dependencies separate and avoid conflicts between different projects. For example, let's install pandas in the venv we just created:
(myenv) pip install pandas
You can also use pip freeze command to see all the packages installed in the environment.
(myenv) pip freeze
This should show the following output (considering you installed pandas):
numpy==1.24.1
pandas==1.5.3
python-dateutil==2.8.2
pytz==2022.7.1
six==1.16.0
It's also possible to export the packages installed in an environment to a requirements file, which you can use to recreate the environment on another machine or share with other team members.
(myenv) pip freeze > requirements.txt
TL;DR
In conclusion, virtual environments in Python are a valuable tool for managing dependencies and isolating different projects. With the built-in support for virtual environments in the latest version of Python, it's easy to create and manage isolated environments for your projects. This can help you avoid conflicts between different projects and ensure that your dependencies are consistent across different development environments.