Before we jump into Virtual Environment (VirtualEnv) let’s consider a situation. Let’s imagine there is a python application which requires version 1.2.0 of library ‘ABC’ installed. So, this is a dependency. Now, let’s imagine there is another python application which requires version 1.2.1 of library ‘ABC’. Technically speaking it is impractical to install both versions of the same library at one place because, latest installation will override previous installation. Also, there can be a possibility where two different python applications need two different libraries. In these scenarios python virtual environment comes handy.
Virtual Environment is nothing but an application that creates a mirror image of the a python installation. Or in other words a localized installation of python for an application which has specific dependencies. You will need to install Virtual Environment as Python does not provide it during the installation. It is very simple to install it.
Command to install Virtual Environment:
$ pip install virtualenv
Now, let’s consider your Python installation is not listed in PATH during installation (I do this because I have multiple versions of Python installed!). In this case all you need to do is locate pip.exe in Python installation and run following command.
$ [python installation directory]/Scripts/pip.exe install virtualenv
Installation in Visual Studio Code:
Well, you don’t need Visual Studio Code to install virtual environment. But, still I want to show how to do it for enthusiasts. While using Python with Visual Studio Code (please read this tutorial to see how to setup Visual Studio Code to debug Python), you don’t need to open the command prompt. There is a terminal tab at the bottom which can be used as command prompt.
After installing virtual environment using PIP let’s see how to create Virtual Environment in Python. It is very simple to create python virtual environment. Steps to create python virtual environment.
and run following command
python3 -m venv [Path for virtual environment]
If Python installation is not in PATH then you will need to run following command
[Python installation directory]/python.exe -m venv [Path for virtual environment]
This command creates a virtual environment at given directory.
Typically you will need to run activate.bat in <Virtual Env>/Scripts to activate the Virtual Environment. But, fortunately, while using Visual Studio Code you DON’T need to run activate.bat. All you need to do is set the pythonpath in settings.json as <Virtual Env Dir>/Scripts/python.exe (check this tutorial to get further information) and Visual Studio Code takes care of rest.
This is how you can install, create and setup Virtual Environment. Once Pythonpath is set rest of the things remain same.
Thank you! Please do let me know if you have any questions, queries or suggestion in the comments section below.