Python Virtual Environment

Every developer would run into the dependency issues one day or other in their projects. Having silent failures or unknown and hard to debug issues that may arise due to the fact that the dependency module versions are incompatible.

So is the reason, for python development we have the requirements.txt where in we can specify modules and their versions our project is dependent or compatible to work on. But we need to sandbox these dependencies just for the project at the hand. If not adhered, and the modules are installed globally, problems comes up if two different projects require different versions of the same dependency module. So python has an excellent concept underneath its architecture called virtual environment.

What is this Virtual Environment? How is it accomplished?

The idea of sandboxing the entire development framework related to a particular project is the basis for Virtual Environment. This is accomplished by creating a whole new python run time by spawning the basic python development and execution structure and utilizing the python runtime and dependency modules from it.

Pre-requisites

  • Python3 or Python2, we use python3 in here.

How to create one?

python3 -m venv <my_virtual_env_name>.

For example, python3 -m venv myvenv

How to enable the virtual environment?

. ./myvenv/bin/activate

The above command results in activating the myvenv virtual environment that can be confirmed by myvenv prefix on shell as shown below

Now we can install all the project specific dependency modules with the command

pip install -r requirements.txt

And these will be only installed for this virtual environment.

Deactivate

We can come out of this virtual environment any time by executing the following command

deactivate

Once done successfully, the myvenv prefix is gone from the shell as shown above.

Happy Coding !!!

Every developer would run into the dependency issues one day or other in their projects. Having silent failures or unknown and hard to debug issues that may arise due to the fact that the dependency module versions are incompatible. So is the reason, for python development we have the requirements.txt where in we can specify…

Leave a Reply

Your email address will not be published. Required fields are marked *