Python is a high-level programming language, widely used for system programming. It is available for all popular operating systems. You can install more than one Python version on a single system. Once you have installed multiple Python versions, you can switch the default Python with the update-alternatives tool.
All the Python developers are recommended to use a virtual environment for the applications. Which provides an isolated environment for the application with a defined Python version.
Switch Python Version on Ubuntu & Debian
The update-alternatives command-line tool is to create and maintain symbolic links for the default commands. With the help of this, we can easily switch commands to different versions. For, this tutorial, Python3.9, and Python2.7 are installed on a Debian system. We will create a group for both commands and set symbolic links.
- Create a symlink from /usr/bin/python2.7 to /usr/bin/python and set the group name as “python”. Later, group name will be used to switch links.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1Outputupdate-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
- Change the symlink link to /usr/bin/python3.9 for /usr/bin/python and set the group name to “python”. The group name must be same for all python versions.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 2Outputupdate-alternatives: using /usr/bin/python3.9 to provide /usr/bin/python (python) in auto mode
- Repeat step 2 to add more Python version to group, which is already installed on your system.
- At this point, You have added two python binary versions to the group name “python”. Now, you can easily switch to any version with the following commands. Here “python” is the group name defined in the above commands.
sudo update-alternatives --config pythonOutput: [Select on option]There are 2 choices for the alternative python (providing /usr/bin/python). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/bin/python3.9 2 auto mode * 1 /usr/bin/python2.7 1 manual mode 2 /usr/bin/python3.9 2 manual mode Press
to keep the current choice[*], or type selection number:
In this above output Python, 2.7 is set as the current version. To change this to Python 3.9, you need input 0 or 2 and hit enter.
- That’s it. The current Python version is changed on your system. Just type the following command to view the correctly active Python version.
python -VOutputPython 3.9.2
You can add multiple Python versions to a group (Steps: 01 & 02) and easily switch between them.
In this tutorial, you have learned about switching the default Python versions on your Ubuntu and Debian Linux systems. Instead of switching version you can also configure Python virtual environment for your applications.