Python Virtual Environment
Introduction
A virtual environment helps to separate dependencies required by different projects by creating an isolated environment. This is an important tool used by most python developers.
Why virtual environment is required?
Now let us consider a situation where a user is working on two projects in which one project needs Django 4.0 and the other project uses Django 4.1. So we create an isolated virtual environment to separate both dependencies required by the project.
When and where to use a virtual environment?
Now in Python, by default, in our system every project stores and retrieves site packages (third-party libraries). Now does this matter, then how?
Now in the above example, we considered two versions of Django as dependencies. Now, this problem is real for python as python can not differentiate between two versions of a library, and both versions will exist in the same folder with the same name.
Now in a situation like these, virtual environments come into play. To solve this problem, we create two isolated environments for both of the projects. Also, there is no limit to creating virtual environments because they are directories and inside there are only a few scripts. We should create a virtual environment for python-based projects so that the dependencies for every project are separated from each other.
Virtual environments working
In Python, there is a module named “virtual” which is a tool to create virtual environments in python. This module creates a folder that contains needed executable files to use the package that a Python project requires.
Installing the virtualenv
$ pip install virtualenv |
Testing the installation
$ virtualenv --version |
To create a virtual environment using the code below:
$ virtualenv my_name |
After the command gets executed, a directory is created named my_name. Now this directory contains all the necessary executable files to make use of the package that a project needs. In this directory, all the libraries get installed.
Now In Python 3, if we want to specify the interpreter, then use the following command:
$ virtualenv -p /usr/bin/python3 virtualenv_name |
For Python v2.7, to create a virtual environment, use the following command:
$ virtualenv -p /usr/bin/python2.7 virtualenv_name |
Now we need to activate this virtual environment. The command mentioned below is used to activate an environment.
$ cd <envname> |
Note: source is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows).