Why
Virtualenv let you create virtual Python environments.
The environment created is a complete sandbox: everything we install or remove from that environment only exist there and all the other environments are not affected.
Each environment created is completely separated from the global package directory of the system.
I use the Python environments to switch between Python2 to Python3 with ease.
Installation
I use pip
as the Python Package Manager which you can easily find how to install on the internet.
install the Virtualenv package
python -m pip install virtualenv
Create an environment
I mostly use 2 distinct environments with a specific version of Python on each
virtualenv -p $(which python3) /home/clobee/myenv/python3
virtualenv -p $(which python2) /home/clobee/myenv/python2
Usage
Each time I need a specific environment, I simply call the following command
source /home/clobee/myenv/python2/bin/activate
My commands are actually used via aliases
alias py2v="source /home/clobee/myenv/python2/bin/activate"
alias py3v="source /home/clobee/myenv/python3/bin/activate"
Here notice how changing environment is easy
When I need to get out of a virtual environment, I simply have to issue the following command
deactivate
Packages
All packages installed into a specific environment are only accessible in that environment. Outside of the virtual environment, the standard Python installation packages are what being used.
Let’s install a package
Now let’s list our available packages (in our current environment)
We can see our package Django which came with dependencies.
Now let’s get out of our virtual environment to see the packages install on the main Python instance
To remove all installed packages, we can execute this command.
pip freeze --local | xargs pip uninstall -y
Or we can simply uninstall a specific package
pip uninstall django