How to create Virtual Environment?

Step – 1

Open your terminal and create a directory to store all your virtual environments, using the command mkdir Environments which is an acronym of “make directory”.

Now go inside the directory using the command CD which stands for call Directory, CD Environments

Step 2

Now we will use a module named virtualenv to create isolated virtual environments.

But first, let’s install this module by the following command,

pip install virtualenv

If you get an error like pip command not found then you have to install pip package manager first, you can learn this here.

To verify a successful installation run this

virtualenv --version

Now we can proceed to create virtual environments

We will create a virtual environment named myenv.

How to create Virtual Environment if you have two different versions of Python installed in your machine?

To create a Virtual Environment for Python 2.x do the following

virtualenv myenv

For a Python 3 virtual environment type –

python3 -m venv myenv

If you only have Python 3 on your machine do the following

virtualenv myenv

This will also work,

python -m venv myenv

This will create a directory myenv along with directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files.

A virtual Python environment has a similar directory structure to a global Python installation. The bin directory contains executables for the virtual environment, the include directory is linked to the global Python installation header files, the lib directory is a copy of the global Python installation libraries and where packages for the virtual environment are installed, and the shared directory is used to place shared Python packages.

 

The interesting thing here is that these environments  won’t have any existing Python package or module of your computer, you can verify it by navigating into myenv>Lib>site-packages

You will only find the essential tools such as pip, easy install and setup tool, later this directory will hold all the packages and modules you will install in this particular environment and remain isolated from other environments.

To add modules and packages in our Environment, we need to activate it first.

On Windows, run:

myenv\Scripts\activate.bat

On Unix or MacOS, run:

source myenv/bin/activate

Now your command prompt will be prefixed by the Environment name which is, in this case, myenv.

This indicates that our Virtual Environment has been activated.

 

You can install any package here with pip or easy install these packages will be completely isolated to other environments on your device.

To deactivate the environment run the following

deactivate

Now there is no more a prefix in our terminal, which indicates that our environment has been deactivated successfully.