Python version switching under Ubuntu

In the development environment of Ubuntu, due to many incompatibilities between Python 2 and Python 3, we often need to manually switch between Python versions.

sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150

If you want to switch back to Python 2.7, you can use the command:

sudo update-alternatives --config python

Run Python -- version to view the current version of Python being used.

For example, if you are currently using Python 2:

$ python --version
Python 2.7.17

You can use the following command to switch to Python 3:

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150
[sudo] password for ts:
update-alternatives: using /usr/bin/python3 to provide /usr/bin/python (python) in auto mode
$ python --version
Python 3.6.9

To switch to Python 2 again, you can use the following command:

$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3   150       auto mode
1            /usr/bin/python2   100       manual mode
2            /usr/bin/python3   150       manual mode
Press <enter> to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python2 to provide /usr/bin/python (python) in manual mode
$ python --version
Python 2.7.17