Learn Python – How to create a virtual environment in Python- Basic and advance

Python utility will often use the programs and additional modules that do not come as a section of a standard library. Sometimes purposes can also require the specific model of the library to operate a precise task or constant a bug.

The importance of creating virtual environment

Suppose we are developing two purposes that require an older version of the library, and other applications require a new version of libraries in the identical Python installation. Sometimes, it leads to a problem.

In the different words, one Python installation may additionally now not in a position to meet the requirements of every application. The requirement of the more than a few purposes may additionally create battle with each other. For example, – If application A requires version 1.0 and every other software requires model 2.0, so they will create conflict, and the end result is one application unable to run.

To resolve this conflicting requirement, Python provides to create the virtual environment. Application A has its surroundings with model 1.0. Application B has its surroundings with model 2.0, so if we desire to improve software B with version 3.0, this will no longer have an effect on application A’s environment.

Creating a Virtual Environment

The module venv is used to create and manage a digital environment. It is accessible with the most current version of Python. We can determine the place to create a virtual environment and run the venv module as a script with the directory path. Type the following command in your command line and hit the enter button.

python3 -m venv new-env  

The above command will create the new-env directory; it also creates the directory inner the newly created virtual environment new-env, containing a new replica of a Python interpreter.

Note: We can write certainly python rather of python3, due to the fact it is used solely if we have hooked up a range of versions of Python.

All virtual environments are saved in the common directory region venv folder. Once we create the digital environment, we have to set off it by using typing the following command.

On Window, Press enter after typing


On UNIX or MacOs, run:

source new-env/bin/activate  

After activating the digital environment, it will exchange the shell prompt’s to tell what virtual surroundings we are using.

Managing Packages Using pip

We can install, upgrade, and delete the libraries in activated digital environment using the Python package supervisor known as pip. For example –

(new-env) $ pip install requests==2.6.0  
Collecting requests==2.6.0  
  Using cached requests-2.6.0-py2.py3-none-any.whl  
Installing collected packages: requests  
Successfully installed requests-2.6.0  

If we re-run the previous command, it will display the required model is already installed.