Python version and environment management in Ubuntu 16.10

In the Setting up Virtual Development Environments for Python post, we discussed the use of pythonbrew for managing Python versions and their related virtualenvs. If you do enjoy pythonbrew, then be sure to check out pythonz which is now the active fork of the original project and has resolved almost all issues that I had originally reported.

However, there is another alternative called pyenv which has several significant advantages. Probably one of the biggest is the fact that pyenv doesn’t depend on Python 2.6+ to be installed. Many OSs (e.g. SLES 10 and CentOS 5) come with Python 2.4 pre-installed. In addition, pyenv implements automatic switching of Python version or virtualenv based on the directory you’re in.

So let’s get started!
Open a new terminal instance and install all build dependencies like this:

$ sudo apt-get install curl git-core gcc make zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev libssl-dev python3-pip

Install Pyenv

$ curl -L | bash

Once installation completes, you’ll be presented with some code that should be added to your ~/.bashrc file:

export PYENV_ROOT="${HOME}/.pyenv"

if [ -d "${PYENV_ROOT}" ]; then
    export PATH="${PYENV_ROOT}/bin:${PATH}"
    eval "$(pyenv init -)"

Simply add this code to the end of your ~/.bashrc and then source your profile to have these additions loaded.

$ source ~/.bashrc

Install a Python version of your choosing

$ pyenv install 3.6.1

This will install Python version 3.6.1 into ~/.pyenv/versions
Now you can change the local or global version of Python

$ pyenv versions
* system

$ pyenv global 3.6.1

Creating virtualenvs is also easy and extremely well integrated into pyenv:

$ pip install virtualenv 
$ pip install virtualenvwrapper 
$ git clone ~/.pyenv/plugins/pyenv-virtualenvwrapper

To setup a virtualenvwrapper into your shell, just run pyenv virtualenvwrapper. For example

$ pyenv virtualenvwrapper

Add this code to your ~/.bashrc 

export WORKON_HOME=~/.ve # Directory four your env (optional)

Once again

$ source ~/.bashrc

Create your env

$ mkvirtualenv env1


Leave a Reply