Python is a popular programming language used for many purposes. It works on all major operating systems. You can install multiple versions of Python on one system. To switch between these versions, you can use the update-alternatives tool.
It’s recommended for Python developers to use a virtual environment. This helps keep the application environment isolated and uses a specific Python version.
Switch Python Version on Ubuntu & Debian
The update-alternatives tool helps manage default commands and their versions. We’ll use it to switch between Python 3.10 and Python 2.7 on a Debian system. We’ll create a group for both versions and set symbolic links.
- Create a symbolic link from /usr/bin/python2.7 to /usr/bin/python and set the group name as “python”. This group name will be used to switch versions later.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
- Change the symbolic link to /usr/bin/python3.10 and keep the group name as “python”. The group name must be the same for all Python versions.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 2
update-alternatives: using /usr/bin/python3.10 to provide /usr/bin/python (python) in auto mode
- If you have more Python versions installed, repeat step 2 for each version.
- Now you have added two Python versions to the “python” group. You can switch between them using the following command. The group name is “python”.
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.10 2 auto mode * 1 /usr/bin/python2.7 1 manual mode 2 /usr/bin/python3.10 2 manual mode Press
to keep the current choice[*], or type selection number: In the above output, Python 2.7 is set as the current version. To change to Python 3.10, type 0 or 2 and press enter.
- That’s it. The current Python version has been changed. Use the following command to check the active Python version.
python -V
Python 3.10.2You can add multiple Python versions to the group (steps 1 & 2) and switch between them easily.
Conclusion
In this tutorial, you learned how to switch the default Python versions on your Ubuntu and Debian Linux systems. Instead of switching versions, you can also set up a Python virtual environment for your applications.