How to install pyenv on Ubuntu

Well, many of us work with ubuntu. One popular option is to use version 18.04, also called Bionic Beaver. Good choice!
When it comes to development, python comes into the picture. The default python version is provided 3.6.9. Why not experiment a little bit with newer versions like 3.8.5, or the upcoming 3.9?

One option is to use Docker containers. It works.
One option is to install different python versions and use update-alternatives to select the Python version that you like. An excellent guide to implementing an approach like that is described in the following article. It works.

A third option that I use and particularly like is to use pyenv, which is a simple Python Version Management.

Let’s install it. First, start with the prerequisites. In Ubuntu cases:

$ sudo apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev python-openssl git

Then, let’s download the library from GitHub and install it:

$ git clone ~/.pyenv

Then we need to configure the environment, so bashrc come into the picture where we need to import the following lines at the end. No need to edit directly with (say) nano though, just execute:

$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init --path)"\nfi' >> ~/.bashrc

and restart the shell:

$ exec $SHELL

What if you have the sexy zsh instead of the traditional bash? No worries, just execute in your zsh the following commands:

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

Then, to make the thing work directly? Just source it:

$ source .bashrc

All right, now how I can check that it works? we could ask pyenv to list all available python versions, with the following command:

$ pyenv install --list

Congrats! Your new shiny python version manager is up and running!

When time passes and you read that new python versions are available but you cannot see them in the list, there is a reason. You need to update pyenv with a simple commend. How?

pyenv update

and now your list is up to date!

Yes, all is fine until now, but how I install a new python version? Simple as that:

pyenv install 3.9.5

Easy, uh?

Another way to install pyenv is to use pyenv-installer (I haven’t used though). Finally, an additional very nice guide to follow, which I used also, is this guide

Happy coding!