If you need to install Python 2 on Ubuntu, you might encounter some challenges since Python 2 has been removed from Ubuntu 20.04 by default. However, for legacy applications or projects that rely on Python 2, it's still possible to install and configure it alongside Python 3. In this guide, we'll walk you through the necessary steps to get Python 2 up and running on your system.
Step 1: Install Python 2 on Ubuntu 20.04
To begin, SSH into your Ubuntu 20.04 server and update the system:
$ sudo apt update
Now, install Python 2 using the following command:
$ sudo apt install python2
Once the installation is complete, you can verify the installed version by running:
$ python2 -V
Python 2.7.17
Step 2: Check Available Python Versions
After installing Python 2, you can check which Python versions are available on your system. Run this command to list all the Python binaries:
$ ls /usr/bin/python*
You should see output like this:
/usr/bin/python2 /usr/bin/python2.7 /usr/bin/python3 /usr/bin/python3.8
If you'd like to check what alternatives are configured for Python on your system, you can run:
$ sudo update-alternatives --list python
If there’s no output or you see an error, it means no alternatives have been set up yet.
Step 3: Set Alternate Python Versions
To easily switch between Python 2 and Python 3, you can configure them as alternatives using the update-alternatives
command. This way, you can set which version of Python should be used by default on the system.
To configure Python 2, run:
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
Next, add Python 3 as an alternative:
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2
Here, the number at the end (e.g., 1
for Python 2 and 2
for Python 3) represents the priority of the version. The higher the number, the higher the priority. You can confirm the alternatives are correctly configured by running:
$ sudo update-alternatives --config python
This command will allow you to select the default Python version interactively.
Step 4: Verify the Configuration
After configuring the alternatives, verify which Python version is currently active by running:
$ python -V
This will display the Python version currently set as the default. You can switch between Python 2 and Python 3 at any time using the update-alternatives
command.
Conclusion
Even though Python 2 is no longer included in Ubuntu , you can still install and configure it manually. This is particularly useful for legacy projects that require Python 2. Using the update-alternatives
command makes it easy to manage both Python versions and switch between them as needed.
With these steps, you’ll be able to install Python 2 on your Ubuntu system and work with both Python 2 and Python 3 in a flexible environment.