Friday, January 1, 2016

Build your own python version on Raspberry Pi

This post will provide a tutorial on how to install a specific python version on the raspberry pi. By default, raspbian does only provide a two python versions. At the time of writing, these python versions are respectively python 2.7.9 and python 3.4.2. Therefore, the available python versions lack support for the new async and await support introduced in python 3.5. This post can also be usefull if you need to build a specific older version of python for compatibility reasons.
You can already find some tutorials for building python 3.5 on the raspberry pi 2. However, this tutorial overwrites the system python version and so potentially it can break other programs.
In this tutorial, pyenv will be used to build and maintain different python versions next to each other.

Prepare the system

As a good practice, first update/upgrade the system packages to the latest versions.

$ sudo apt-get update
$ sudo apt-get upgrade -y
$ sudo apt-get dist-upgrade

Some specific software packages will be needed as a dependency to build python (or optional python modules).

$ sudo apt-get install build-essential libncursesw5-dev libgdbm-dev libc6-dev zlib1g-dev libsqlite3-dev tk-dev libssl-dev openssl libbz2-dev libreadline-dev

Installing pyenv

In this post, everything will be installed in the home folder of the current user. Feel free to adapt the install location to a different location on the system if it should be shared with different users. Installing pyenv and pyenv-virtualenv is as simple as cloning the git repos and set some paths in the environment. Note that pyenv provides full code completion on the shell!

git clone ~/.pyenv

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.profile
echo 'eval "$(pyenv init -)"' >> ~/.profile

Now, relaunch the shell (or logout and login) to initialize pyenv in your shell.

Installing python

Finally, a specific python version can be installed in the pyenv folder. In this case, python 3.5.1 is being installed. Note that this can take a while.

$ pyenv install 3.5.1
Downloading Python-3.5.1.tgz...
Installing Python-3.5.1...
Installed Python-3.5.1 to /home/pi/.pyenv/versions/3.5.1

A specific python version can now be activated with the following commands:

pi@raspberrypi:~ $ pyenv versions
* system (set by /home/pi/.pyenv/version)
pi@raspberrypi:~ $ pyenv shell 3.5.1
pi@raspberrypi:~ $ python --version
Python 3.5.1

No comments: