Thursday, September 16, 2021

Python Virtual Environment

  One of the cool features that python has, is the ability to create a virtual environment similar to the virtual OS mechanism. The virtual environment is like a sandbox with its own site-packages and other libraries mimicking the python installed in the system. This kind of environment helps the developer/engineer to understand the deployment issues of the python library by installing and debugging the library dependencies. This step helps in identifying and fixing the dependency issues before deploying them into production environments. Also, as this entire stuff happens in an isolated virtual environment, he/she doesn't need to worry about the false results by OS level setup.

Let's see how we can create a virtual environment. To be honest, it is pretty simple, all you have to do is to make sure that the venv library is present, but of course, it is a default executable installed during python installation. You can check it by typing the command shown in the below snapshot.


Now that we have verified the venv presence, let us create a sample virtual environment with the name blogvirtual. The command looks similar to the above with an additional argument stating the name of the virtual environment. Refer to the below snapshot for the command.

Once the command gets successfully executed, it creates the folder in the directory in which you have requested the virtual environment(venv). The below snapshot shows the folder created by our command.

Now it's time to activate it. Inside the folder under scripts, we have an executable called "activate" which when run initiates the virtual environment.


So as you can see in the above snapshot, after the successful activation of venv. The Directory path is now prefixed with our virtual environment (blogvirtual in this case).

Let us see what are libraries available in it. You can see that it has the basic libraries

Now let us see the libraries installed within the system(refer below snapshot), it is quite a big list. This way we create a virtual environment and use them as per the need.

For more information, you can refer to the official documentation : https://docs.python.org/3/library/venv.html