Computer >> Computer tutorials >  >> Programming >> Python

Creation of virtual environments using Python


A Python package of a specific version may be needed while developing Python based applications. However if this version of same package is installed for system wide use, it might be conflicting with other application’s requirements. Hence it is desired to have side-by-side environments for each purpose to resolve compatibility issues.

Virtual Environments allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally.

The venv module in standard library of Python is used to create virtual environment. A virtual environment is a directory in file system having its own copy of Python interpreter and other scripts. Following command creates a virtual environment in the named directory.

C:\python37>python -m venv e:\testenv

You will find a new directory created as specified. The above can optionally use following switches

--system-site-packages
 Give the virtual environment access to the system site-packages dir.
  --symlinks  
 Try to use sym links rather than copies
  --copies      
  Try to use copies rather than symlinks
  --clear      
   Delete the contents of the environment directory if it exists
  --upgrade    
   Upgrade the environment directory to use this version of Python
  --without-pip  
       Skips installing or upgrading pip in the virtual  environment (pip is bootstrapped by default)

The 'scripts' folder under the ENV_DIR (in this case testenv) contains local copy of Python interpreter, pip installer and scripts to activate and deactivate the environment.

activate
activate.bat
activate.ps1
deactivate.bat
easy_install-3.7.exe
easy_install.exe
pip.exe
pip3.7.exe
pip3.exe
python.exe
pythonw.exe

Activate virtual environment

In order to start Python in the isolated environment, it must be activated first. For this purpose, 'activate.bat' must be invoked from command line.

E:\testenv>scripts\activate

(testenv) E:\testenv>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Name of the virtual environment appears in parentheses to the left of DOS prompt. Now you can Python in virtual environment.

If any package is installed using pip3 utility in virtual environment's scripts folder, it will be locally installed and will not be available for system wide use.

Deactivate virtual environment

To return to normal environment, the virtual environment should be disable using 'deactivate.bat' in scripts folder.

>>> quit()

(testenv) E:\testenv>scripts\deactivate
E:\testenv>

For Python versions before 3.3, use virtualenv which must be installed separately.

The venv module defined EnvironmentBuilder class for programmatically creating virtual environment.