- Upgrade Python to latest version (3.10) on Ubuntu Linux
- Updating Python to the latest version
- Step 1: Check if Python3.10 is available for install
- Step 2: Install Python 3.10
- Step 3: Set Python 3.10 as default
- Fix pip and disutils errors
- Fix Python3-apt
- Install pip & distutils
- Fix pip-env errors when using venv
- Extra
- Как обновить python на Ubuntu
- Подготавливаем данные с локальной версии
- Обновляем Ubuntu на сервере
- Обновляем python на сервере
- Меняем версию python в системе «по умолчанию»
- Устанавливаем новое окружение
- How to Update Python on Ubuntu?
- Conclusion
- About the author
- Omar Farooq
Upgrade Python to latest version (3.10) on Ubuntu Linux
Linux systems come with Python install by default, but, they are usually not the latest. Python also cannot be updated by a typical apt upgrade command as well.
To check the version of Python installed on your system run
python keyword is used for Python 2.x versions which has been deprecated
- Update Python to the latest version
- Fix pip & other Python related issues
- While doing the above two, ensure your Ubuntu which is heavily dependent on Python does not break
Updating Python to the latest version
Ubuntu’s default repositories do not contain the latest version of Python, but an open source repository named deadsnakes does.
Python3.10 is not officially available on Ubuntu 20.04, ensure you backup your system before upgrading.
Step 1: Check if Python3.10 is available for install
sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update
Check if Python 3.10 is available by running
This will produce the below result, if you see python3.10 it means you can install it
Step 2: Install Python 3.10
Now you can install Python 3.10 by running
sudo apt install python3.10
Now though Python 3.10 is installed, if you check the version of your python by running python3 —version you will still see an older version. This is because you have two versions of Python installed and you need to choose Python 3.10 as the default.
Step 3: Set Python 3.10 as default
Steps beyond here are tested on Ubuntu 20.04 in VM & WSL2, but are experimental , proceed at your own risk.
Changing the default alternatives for Python will break your Gnome terminal. To avoid this, you need to edit the gnome-terminal configuration file.
Open the terminal and run:
sudo nano /usr/bin/gnome-terminal
In first line, change #!/usr/bin/python3 to #!/usr/bin/python3.8 . Press Ctrl +X followed by enter to save and exit.
Then save and close the file.
Next, update the default Python by adding both versions to an alternatives by running the below
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 Now run
sudo update-alternatives --config python3
Choose the selection corresponding to Python3.10 (if not selected by default).
Now run python3 —version again and you should see the latest Python as the output.
Fix pip and disutils errors
Installing the new version of Python will break pip as the distutils for Python3.10 is not installed yet.
Fix Python3-apt
Running pip in terminal will not work, as the current pip is not compatible with Python3.10 and python3-apt will be broken, that will generate an error like
Traceback (most recent call last): File "/usr/lib/command-not-found", line 28, in <module> from CommandNotFound import CommandNotFound File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module> from CommandNotFound.db.db import SqliteDatabase File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module> import apt_pkg ModuleNotFoundError: No module named 'apt_pkg'
To fix this first remove the current version of python3-apt by running
sudo apt remove --purge python3-apt
DO NOT RUN sudo apt autoremove as it will remove several packages that are required. This may break your system if you’re using GUI, if you’re on WSL2 you can proceed.
Finally, reinstall python3-apt by running
sudo apt install python3-apt
Install pip & distutils
Running pip will still throw an error pip: command not found . We need to install the latest version of pip compatible with Python 3.10.
Also, if try to manually install the latest version of pip, it will throw an error like
ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.10/distutils/__init__.py)
Or you might also see an error stating No module named ‘distutils.util’ . This is because the distutils module is not installed yet, to install run the below command
sudo apt install python3.10-distutils
Now you can install pip by running
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py sudo python3.10 get-pip.py
If you get an error like bash: curl: command not found then you need to install curl first by running sudo apt install curl
Now you can run pip and you should see the output of pip —version
Fix pip-env errors when using venv
When you try to create a new virtual environment using python -m venv env , you may into the following error.
Error: Command -Imensurepip--upgrade--default-pipYou can fix this by reinstalling venv by running
sudo apt install python3.10-venv
All should be done now. It is complicated, but this is how you update Python to latest version.
Extra
If you have oh-my-zsh installed, you can avoid typing out python3 by running
Now you can run your files with py or python .
Как обновить python на Ubuntu
Admin 30.10.2022 Linux, Python, Ubuntu
Обновление на новые версии это всегда «весело». Вместе с новым функционалом понадобится убрать устаревшие функции, обновить потерявшие совместимость модули и в целом проделать большую работу.
Подготавливаем данные с локальной версии
Сначала обновляем версию локально, тестируем. Фиксируем изменения всех зависимостей командой:
Обновляем Ubuntu на сервере
Обновим систему и пакеты в ней:
Обновляем python на сервере
Если сразу запустить обновление, то возникнет ошибка:
sudo apt install python3.10
Чтение списков пакетов… Готово
Построение дерева зависимостей
Чтение информации о состоянии… Готово
E: Невозможно найти пакет python3.10
E: Не удалось найти ни один пакет с помощью шаблона «python3.10»
Сначала установим необходимые компоненты для добавления пользовательских PPA:
Добавим PPA-репозиторий deadsnakes/ppa в список источников диспетчера пакетов APT:
Запустим обновление APT для обновления менеджера пакетов — появится новый импортированный PPA:
Теперь можем установить новую версию python 3.10:
Проверим установленную версию:
Также проверим текущую версию по умолчанию:
Установим дополнительные модули стандартной библиотеки (venv):
Также могут пригодиться и другие модули:
sudo apt install python3.10-distutils -y
sudo apt install python3.10-lib2to3 -y
sudo apt install python3.10-gdbm -y
sudo apt install python3.10-tk -y
Многие дополнительные модули python нужны для работы библиотек, без них они не установятся и будут вылезать ошибки.
Меняем версию python в системе «по умолчанию»
По умолчанию python будет указывать на старую версию.
Например, Python 3 указывает на Python 3.8. Это значит, что когда мы запустим python3, он будет выполняться как python 3.8, мы же хотим выполнить его как python 3.10.
Для этого добавим альтернативы:
sudo update-alternatives —install /usr/bin/python3 python3 /usr/bin/python3.8 1
sudo update-alternatives —install /usr/bin/python3 python3 /usr/bin/python3.10 2
Устанавливаем новое окружение
Переименовываем старую директорию окружения (мы должны находится в директории сайта с виртуальным окружением):
Затем в этой директории создаем новое виртуальное окружение:
How to Update Python on Ubuntu?
Python is a very top interpreted semantic used in Computer programming. It’s not only diverse but also very simple and easy to use, implement and learn by any programmer. It doesn’t take much time to learn and get skilled in it. You can use it in any operating system i.e., Windows and Linux. Python comes up with many versions that can be installed on our systems. So, within this guide article, we will discuss the ways to update the old Python version to the newest one in Ubuntu 20.04 Operating System. So, let’s get started to see it.
First of all, you want to open the Ubuntu 20.04 shell terminal application on Ubuntu 20.04 desktop. For that, you have to utilize the everlasting shortcut key “Ctrl+Alt+T” on the desktop of Ubuntu 20.04.
The shell application will be opened. Now, you have to check the version of a Python language already installed on your system. For this, you will be executing a version command of Ubuntu 20.04 with the keyword python. The command has been shown in the attached screenshot of the terminal. It clearly shows that any version of Python language is not configured in our system and we need to install it by ourselves. Many commands can be used.
So, we have to install the python version on our system supported by Ubuntu 20.04. Before that, we have to update our system. The apt package will be utilized in the update command to do so. The command is displayed in the image as well. The execution of this apt command leads us to enter the sudo password of our system. After adding the password, our system will update itself and its packages. The command and the process have been shown in the image.
It’s time to install the python old version on our system first. This is necessary to be done because we have to then update the python to the newest version after that. We have been installing Python version 2 on our system using the apt installation command displayed below.
After making the package ready, it will pause the process of installation for a while to ask us to affirm our action. It will let us know that 16.5 MB of space will be occupied by this package and if we want to continue installing it. So, we tapped “Y” to continue the installation process.
The installation process will start progressing. After it reaches 100 percent, it will be completed. Let’s just update the Linux system once again with the “apt” package.
After the successful installation of Python, we will be checking the version of python that has been installed. The version command has been used here once again as illustrated from the image below. We have used the “python2” keyword to check the installed version of Python 2.
When we have checked for the Python 3 versions on your system, it shows that the Python 3.8.2 version has also been installed with Python 2. While Python has come up with the Python 3.9 version as well. So, we need to upgrade this latest version to Ubuntu 20.04.
Let’s begin with the update of Python 3. First of all, you need to install all the required packages and repositories that are prerequisites for Python 3.9. Instead of listing all packages in the installation command, we have to just use the keyword “software-properties-common” in the instruction. We have done it in the command and the process has been started.
It will also pause the installation of required packages to affirm your action. It’s been informed that this process will take 14.3 kb of space on your system and do you want to continue it. So, we have added “y” and tapped the “Enter” button to start the process of installation.
The packages will be installed and configured on our system one by one and may take up to 5 minutes. The completion of this process has been shown in the small image below.
Before the installation of Python 3.9, you must have to add the “ppa” repository to your system. Without “ppa”, you will be unable to install Python 3.9. You need to use the “add-apt-repository” command of an apt package to do so. You have to use the “ppa:deadsnakes/ppa” keyword within your command with sudo privileges. Execute the command shown in the image below and it will set your system for new Python versions.
After a few seconds, the process of adding ppa will ask you to press the Enter button to start adding ppa requirements and packages i.e., prerequisites. we pressed Enter and the system installed the ppa package on our system. The output is shown in the attached photo.
Now, we cannot use the simple apt installation command with the keyword “python3.9” to install the latest python version. We have to install the Python environment variables and development interface with the keywords “python3.9-venv” and “python3.9-dev” as below.
Again, the system has been asking to tap “y” to affirm the action of installation as it takes 114 MB space on our Ubuntu system. We have tapped “y” and pressed the “Enter” key to continue.
The system has started upgrading the python. The process will take some to complete as it will also install the development environment along with the environment variables of Python 3.9.
After the complete installation, we have utilized it to check the Python version. We have found that the Python 3.9 latest version is now configured on our Ubuntu 20.04 system fully.
Conclusion
This article contains all the information and process regarding the update of Python in the Ubuntu 20.04 system. We have started from the very basics by installing the old version of Python on our system i.e., python2. Then, we have shown the way to update the Python version and upgrade it to version 3.9 by utilizing some commands. We hope you liked this article.
About the author
Omar Farooq
Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.