Virutal environment is an useful utility for python to install packages locally and not globally so your system remains clean after installing multiples packages. It is recommended to avoid future conflicts between packages.
To install virtual environment you just have to type:
$ pip install virtualenv
To check the installation:
$ virtualenv --version
To create a virtual environment for a project:
$ cd projectFolder
$ virtualenv projectName
Now you can see what virtualenv has installed in the projectFolder. Basically, it has created a subfolder named projectName and inside it you locate the next folders:
bin include lib local man share
In the bin folder a copy of your pip binary has been created which will manage future installations in this local environment. You can also specify the python interpreter to be used on this virtual enviroment. There are two ways to define the interpreter:
1st method -> $ virtualenv -p /usr/local/pyton3 projectName
2nd method -> $ echo 'export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3' >> ~/.bashrc
In the second method you are setting the python interpreter globally.
To activate the virtual environment, you must type:
$ source projectFolder/bin/activate
To deactivate you only must type:
$ deactivate
Once you have activated the environment you can now install all the packages required for your project and they will be installed locally within your project folder instead of your system.
This other utility to manage your virtual environments which offers more control. To install it, you must have previously installed virtualenv.
$ pip search virtualenv
virtualenv (15.1.0) - Virtual Python Environment builder
INSTALLED: 15.1.0 (latest)
$ sudo pip install virtualenvwrapper
$ mkdir ~/Envs
$ export WORKON_HOME=~/Envs
$ source /usr/local/bin/virtualenvwrapper.sh
To export the WORKON_HOME variable and make it permanent, include it on your bashrc file:
$ echo 'export WORKON_HOME=~/Envs' >> ~/.bashrc
Create a virtual environment:
$ mkvirtualenv projectName
It creates the projectName folder for the virtual environment inside ~/Envs directory.
Work on the virtual environment:
$ workon projectName
There is an alternative to create the virtual environment but it also creates the project directory inside the $WORKON_HOME directory:
$ mkproject projectName
Deactivate is the same as the virtualenv:
$ deactivate
To remove the project from the $WORKON_HOME you must deactivate it and then:
$ rmvirtualenv projectName
(To delete in the case of virtualenv you only have to delete recursively the entire folder where the project is located.)
List all the virtual environments:
$ lsvirutalenv
Navigate into the directory of the currently activated virtual environment, so you can browse its site-packages, for example.
$ cdvirtualenv
Like the above, but directly into site-packages directory.
$ cdsitepackages
Shows contents of site-packages directory.
$ lssitepackages