How to create a Virtual Environment in Python?
What is a Virtual environment in Python?
A virtual environment as the name suggests is created virtually in your system so you can install project-based dependencies and packages. It is similar to container, each virtual environment will have own package and files but isolated from each other.
Why do we need a Virtual Environment?
Suppose you are working on two different projects and each project has the different requirements for the specific module. For example, one project needs v1.0 of azure module and another project needs v2.0 and you have a single system to run both the project.
One way is to run both the projects with different dependencies on the same system is to use Virtual machines or containers but python provides its own virtual space to create separate project and install dependencies and you can destroy that when work is over. It is so simple !!!
Demo
In this article, we are going to install two different virtual environments on a single system (Windows) that will have az.mgmt.compute module different versions. Before creating your virtual environment, make sure Python is installed in the system (https://www.python.org/downloads/ ).
- Open Terminal on the windows OS and type the below command.
python -m venv MyTestVENV
OR
python3 -m venv MyTestVENV
Here MyTestVNEV directory will be created.
- Browse to that directory and you will see the default files and directory created supported for that virtual environment.
- To activate the virtual environment, browse the Scripts directory and there are different activation files.
- You can directly run activate on any terminal or activate.bat (cmd / PowerShell) or Activate.ps1 (PowerShell) terminal.
- Once you run, you will see the name of the virtual environment in the round brackets. That means you are inside the virtual environment world.
- Now install the az.mgmt.compute module latest version.
pip install azure-mgmt-compute
- Once you install the module, get out of the virtual environment using the deactivate command.
- Similarly, create the second virtual environment to install different compute module versions as shown in the steps below.
c:\>python -m venv MyTestVNEV2
c:\>cd MyTestVNEV2\Scripts
c:\MyTestVNEV2\Scripts>activate
(MyTestVNEV2) c:\MyTestVNEV2\Scripts>pip install azure-mgmt-compute==25.0.0
- Run the pip freeze command on both the virtual environments and you will see the different compute modules are installed in their own space.