Setting up a virtual environment

pyenv

In order to build a virtual environment which has a unique python version, we first need to download a specific python version. The easiest way of doing this is by using pyenv.

After following the installation instructions, we may download a specific python version with the following,

$ pyenv install 3.7.0

This will download the python==3.7.0 binary file to the following directory: ~/.pyenv/versions/3.7.0/bin/python3.

Creating a virtualenv

virtualenv is a tool used to create isolated python environments by creating a folder which contains all of the necessary executables to install multiple python packages.

A virtual environment called myenv may be created in the directory ~/virtualenvs with the following,

$ virtualenv -p ~/.pyenv/versions/3.7.0/bin/python3 ~/virtualenvs/myenv

Where the flag -p allows for you to specify the python interpreter of your choice – here we use python==3.7.0 installed above.

We may then activate this virtual environment with,

$ source ~/virtualenvs/myenv/bin/activate

Packages can then be installed using the pip command,

(myenv) $ pip install numpy

Once you are done working in the virtual environment, you can deactivate it.

$ deactivate

Installing a jupyter kernel

It is often convenient to use jupyter notebooks for a specific virtual environment. By default, only the base environment will have a useable kernel. We may install a kernal for a specific virtual environment with the following,

$ source ~/virtualenvs/myenv/bin/activate
(myenv) $ pip install ipykernel
(myenv) $ ipython kernel install --user --name=myenv

You may then launch your jupyter notebook (or refresh if already open) and a kernel called myenv will be available for you to use. This will then have all of the packages installed in your virtual environment available for use.