How to change the default python version in Ubuntu

·

2 min read

I make this short note for myself because I often change or have to deal with new OS such as Ubuntu.

In Ubuntu (and in some other OSes), it is possible to have multiple versions of pythons, e.g, python2.7, python3.10, python3.11. If you type python --version or python3 --version, you may get the python version you do not expect. In that case, you can change the default version using the update-alternatives command.

First, let's check the python versions we have installed using

ls -la /usr/bin/python*

You may get something like this:

lrwxrwxrwx 1 root root       9 Mar 13  2020 /usr/bin/python2 -> python2.7
-rwxr-xr-x 1 root root 3662032 Jul  1  2022 /usr/bin/python2.7
-rwxr-xr-x 1 root root 7163864 Dec  7 10:11 /usr/bin/python3.11
-rwxr-xr-x 1 root root 5494584 Nov 14 21:59 /usr/bin/python3.8

Now, we want python3.11 to be the default python version. We use the update-alternatives command as follows.

 sudo update-alternatives --install /usr/local/bin/python python /usr/bin/python3.11 2 
 sudo update-alternatives --install /usr/local/bin/python python /usr/bin/python2.7 1

The alternative with the highest priority (the last part of each command above) will be the default. So if we type python --version then we will get python3.11.

If we want to change the python version again, we don't have to configure it like the above ones. Instead, we use

sudo update-alternatives --config python

We then need to specify the number referring to the python version we want, e.g., number one for python2.7.

There are 2 choices for the alternative python (providing /usr/local/bin/python).

  Selection    Path                 Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.11   2         auto mode
  1            /usr/bin/python2.7    1         manual mode
  2            /usr/bin/python3.11   2         manual mode

Press <enter> to keep the current choice[*], or type selection number:1

With python --version , we will get pyhton2.7.