How to Easily Switch Between Python Versions in Ubuntu
It had been reported that changing the default python version with update-alternatives breaks the shell, so use it at your own risk!
Recently my team has stopped supporting python 2.7 and only supports python version 3.5 and above. For testing purposes, I had to install all three (at the time of writing this post) 3.5, 3.6, 3.7, 3.8, and 3.9 in the same system. But it was a bit of a hassle to delete and create a new link for /usr/bin/python3
and sometimes it messes things up.
To be on the safe side, I have spent a bit of time testing different methods of switching between python versions. There are a couple of different ways to do this but the following is the one I found easy to use and had no apparent side effects (in my case) on the system.
NOTE
Tested on ubuntu 16.04, 18.04, 20.04
Once all three versions of python is installed. It’s time to configure the alternatives.
Add Python Versions to Update Alternatives
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.6 2
sudo update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.7 3
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 4
sudo update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.9 5
/usr/local/bin/python3.6
or /usr/local/bin/python3.9
is the full path to the python binary and 1
, 2
, 3
, 4
and 5
at the end is the priority level.
sudo update-alternatives --config python3
Choose a version and put the digit as a selection number and press ENTER.
Check Python Version
Now you can check if the python3
is pointing to the right version or not by using the following command
python3 --version
Enjoy!