Chapters

Python

Posted by: Jaspreet

Last Updated on: Nov 30, 2021


Create Virtual Environment In Python


Chapters



Having python virtual environment helps us to create 2 different environment (or ecosystem) of libraries, that don't interfer with each other. E.g. lets assume you have pandas (a python library) installed in your computer, version X.y, for the currenlty ongoing project, i.e. Project Y that you're working on. Now, if you start a new project, i.e. Project Z, you might want to install some new libraries for Project Z.

The issue that could arise here could be, Project Z might have the requirement to use python library pandas X.z or greater. However, Project Y mandates the use of python library pandas X.y or lower. Now, this could cause a lot of problems when you try to switch between projects, as the library dependencies will make you constantly install-uninstall libraries, depending on which project you're working on.

To avoid this hassle, for a single computer, we can host 2 (or more) isolated environments, where libraries of 1 environment wouldn't interfere with the libraries of the other environment, i.e. now you could use python library pandas X.y & pandas X.z simultaneously, without the need to reinstall again and again for project specific needs, as we've created isolated environments for our respective projects, as per thier needs.
Now, lets see how can we achieve it

1) CREATE

Go to your project's root directory and open cmd prompt/terminal there
* In windows, go to project's root directory, press Alt+D and then Home, then enter "cmd" at the starting of the address bar and hit enter ** If facing with "PATH not found" or "Add directory folder to the PATH", you need to add the directory, where the 'pip install virtual env' installed your library in. The folder where the library has been installed would be displayed in the cmd prompt or terminal.

Follow this tutorial for guided steps, and then re-enter the command virtualenv myenv

2) ACTIVATE

To use this environment and install any packages, type: This will activate the virtual environment, and now whatever package you install with pip, will stay inside this virtual environment.

3) EXIT

4) SHARE

If you wish to replicate this project or environment in some other system or directory, or wish to share this project with others and want them to smoothly run it, without going through any library dependencies related issue troubleshooting, along witht the code in your project, you may share with them the environment in which this project was built. This will help them to smoothly run it in thier own pc.

To do so simply copying this environment will not work. For that, first activate this environment and create a list of all packages by typing: That is all you need to do to isolate your python project dependencies.

References