InterviewSolution
| 1. |
What is the importance of using a virtual environment? Explain how to setup, activate and deactivate virtual environment? |
|
Answer» When you install Python and add Python executable to PATH environment variable of your OS, it is available for use from anywhere in the file system. Thereafter, while building a Python application, you may need Python libraries other than those shipped with the standard distribution (or any other distribution you may be using – such as Anaconda). Those libraries are generally installed using pip installer or conda package manager. These packages are installed in site-packages DIRECTORY under Python’s installation folder. However, sometimes, requirement of a specific version of same package may sometimes be conflicting with other application’s requirements. Suppose you have application A that uses library 1.1 and application B requires 1.2 version of the same package which may have modified or deprecated certain functionality of its older version. Hence a system-wide installation of such package is likely to break application A. To avoid this situation, Python provides creation of virtual environment. A virtual environment is a complete but isolated Python environment having its own library, site-packages and executables. This way you can work on DEPENDENCIES of a certain application so that it doesn’t clash with other or system wide environment. For standard distribution of Python, virtual environment is set up using following command: c:\Python37>python -m venv myenvHere myenv is the name of directory/folder (along with its path. If none, it will be created under current directory) in which you want this virtual environment be set up. Under this directory, include, lib and scripts folders will be created. Local copy of Python executable along with other utilities such as pip are present in scripts folder. Script older ALSO has activate and DEACTIVATE batch files. To activate newly created environment, run activate.bat in Scripts folder. C:\myenv>scripts\activate (myenv)c:\python37>Name of the virtual environment appears before command prompt. Now you can invoke Python interpreter which create will local copy in the new environment and not system wide Python. To deactivate the environment, simply run deactivate.bat If using Anaconda distribution, you need to use conda install command. conda create --name myenvThis will create new environment under Anaconda installation folder’s envs directory. |
|