Virtual Environment in python
Let’s think of a time when Covid-19 was at its peak. Yes, that time, we all were locked up in our homes, with our family. We cooked what we already had, enjoyed with whatever was available, and depended totally on family members. No one moved out, and all of us functioned well in our homes.
This is exactly what a virtual environment is. Virtual Environment is a tool which keeps our projects and all its dependencies combined isolated from other projects and its dependencies. The Virtual Environment is similar to the bag, which contains all the stuff keeping it separate from the outside world. Virtual Environment is a keeper of all the dependencies, libraries, interpreter, script and everything needed to execute a script.
Isn’t it amazing? But, how can we create this environment? Let’s start by setting our own environment to make the script comfortable amongst other scripts :P
Setting up a virtual environment
We set up a virtual environment in the directory where our script (project) resides. To set up a virtual environment, first direct to the project directory. Now, run the following command:
python3 -m venv venv_name
To work inside the virtual environment, we first need to activate it.
To activate the virtual environment, run the following command:
Now, we have bought a bag, and we are ready to put our belongings into it.
Thus, here you can create a script, execute it and run the script after installing each and every library/ dependency required by the program.
A cherry on the cake:
Whenever you share your code, there is a probability that the other person may or may not have all the dependencies required to execute the script installed in his/ her system.
To ensure that person installs all the requirements, we make a requirements.txt file and run a command to install all the libraries required by the script.
Thus, just before installing any library for the project, make sure that you create your script, and then run the following command:
pip freeze > requirements.txt
Now, check the requirements file inside the directory. It contains all the libraries you installed and which are needed for your script.
Here, you are done. The only thing you need to do is to tell your friend to run :
pip install -r requirements.txt
This command will automatically install all the libraries into the virtual environment, making it easy for others to run the script.
Thanks for reading.