virtualenvwrapper is an excellent tool to manage python virtual environments. It lets you collect all virtual environments into a single directory. It can also activate the virtual environments from any directory with a single command. virtualenvwrapper makes all the hassles of finding the activate file and sourcing it go away. This article explains the installation and configuration of virtualenvwrapper in Linux systems.
This article assumes you are using python 3. If you want to configure virtualenvwrapper for python 2.7, substitute python3 with python2 in relevant places.
Install virtualenvwrapper
Install pip3 if not already installed. For Debian based systems such as Debian, Ubuntu Or Linux mint, run the following command from a terminal.
sudo apt install python3-pip
For Red Hat based systems such as Fedora, Cent OS or Fedora, use
sudo dnf install python3-pip
Once you have pip3 installed, use it to install virtualenvwrapper. Run the following command from a terminal.
sudo pip3 install virtualenvwrapper
Configuring virtualenvwrapper
After installation, you need to do some configurations to make virtualenvwrapper work. First, you will have to create a directory to save all virtual environments. Usually, it is the .virtualenvs directory in your home directory.
mkdir ~/.virtualenvs
Now you have to set this as the home directory for your workon command (You will learn more about workon command in next section). The following command will do that for you.
export WORKON_HOME=~/.virtualenvs
Next, you have to add some configurations to your .bashrc file. Open your .bashrc file using
nano ~/.bashrc
and add the following line at the end of it.
VIRTUALENVWRAPPER_PYTHON='/usr/bin/python3'
source /usr/local/bin/virtualenvwrapper.sh
The above configuration is for Debian based systems. For Red Hat based systems, you have to add
VIRTUALENVWRAPPER_PYTHON='/usr/local/bin/python3'
source /usr/local/bin/virtualenvwrapper.sh
Now, source the updated .bashrc file.
source ~/.bashrc
Creating and Using Virtual Environments
To create a new virtual environment, run
mkvirtualenv name-of-your-virtual-env
This will create a new virtual environment and activate it for you. To deactivate the virtual environment, run
deactivate
To activate your virtual environment again, simply run
workon name-of-your-virtual-env
This will work from any directory. Also, you can have any number of virtual environments and switch between them using workon and deactivate.
If you want to create a virtual environment that uses a different python interpreter instead of the one you configured in your .bashrc file, you can pass it as an argument to the mkvirtualenv command. For example, the following command will create a virtual environment that uses python2.6.
mkvirutalenv my-very-old-env --python=/usr/bin/python2.6
Of course, for this to work, you should have python2.6 installed.