How to update python to latest version and set as default
Install Python normally with the deadsnake PPA:
Check if you can access Python:
If so, create a symlink to set it as "default":
If you don’t have it in apt then you can add special repo deadsnakes Python repo for Ubuntu.
And after adding repo you should have all versions in apt form 2.3 to 3.10
And later you can find path to actuall version
and replace is with python3.9 which you can also find with
But sometimes it is not good idea to replace it because system may need older version and it will not work with newer one. I prefer to use python3.9 when I need 3.9 and python3.7 when I really need 3.7 .
After adding this repo it will also inform you when there will be newer version 3.9.x
Install and Upgrade Python on Ubuntu
The Python language has been gaining popularity for several years, both as a programming and a scripting language.
Ubuntu and almost every other Linux distribution have been shipping with some version of Python for quite a long time.
You can check the version of python with the following command:
Running the command will show the version of Python v3 that you have installed.
Isn't Python already installed?
Well yes, when you install Ubuntu, a version of Python is automatically installed as most system utilities also depend on it.
The problem here is that many people try to run python directly and they will be surprised when their Ubuntu system throws an error:
The thing is that in Ubuntu, the Python version 3.x is installed and its binary is named python3, not python.
Sometimes, the version that is pre-installed, or the latest version that is available from Ubuntu's repositories is older than the one found on python.org.
To check the version of Python that is installed, run the following command in your terminal:
At the time of writing this article, the latest version found on python.org is 3.10.4, which is exactly what I have installed from the first-party repository.
Weirdly, if Python is not found, you might get a similar error:
Codecademy
Install and Upgrade Python
In case you do not have Python installed, fret not. You can easily install it from Ubuntu's software repositories.
Use the apt package manager to install Python. Below is the command to run:
The first command will update the local package list, in case it was out of sync. The second command will install whatever the latest version of Python v3 is available at the moment.
Even if you have Python installed, the 'apt' package manager will install a newer version of Python, if available. This goes without saying, the dependencies will also be installed and/or upgraded as well.
Ubuntu takes care of the Python version it provides. If there are security or maintenance updates, you get them with the system updates. You just have to update your system to get Python upgrades (if there are any from Ubuntu).
Python version in Ubuntu repositories is old?
With the announcement of a new Annual Release Cycle for Python, a new version of Python will be released every year, as opposed to every 1.5 years.
This means the version available in repositories for Ubuntu's LTS versions will not stay "latest and greatest" after a while.
This does not mean that you stop receiving updates to Python altogether. Even if the version of Python is old, you will get all the necessary security updates, including any additional bug fixes.
What should I do?
I recommend you use the version of Python provided by Ubuntu. As previously, Canonical (parent company of Ubuntu) will continue providing necessary updates to your stable version of Python. It includes up-to-date bug fixes and security updates for Python.
I want updates!
In any case, if you want to install a newer version of Python than what is available in Ubuntu's repositories, you have a few options.
The easiest option is to use a third-party PPA. That way, you are out of the hassle of applying necessary patches and compiling every time a new version of Python is released.
Using Deadsnakes PPA (if you really want the latest Python)
The Deadsnakes PPA contains a more recent version of Python packaged for Ubuntu. This means you can install a newer version of Python even if the first-party repositories contain an older version.
A disclaimer from PPA maintainer themselves:
There is no guarantee of timely updates in case of security problems or other issues. If you want to use them in a security-or-otherwise-critical environment (say, on a production server), you do so at your own risk.
Before adding a PPA, the 'software-properties-common' package needs to be installed first. Do that with the following command:
Once the apt repositories manager package is installed, we can now easily add the Deadsnakes PPA. The command to do so is given below:
The PPA is added. Now we need to update the local package list.
Finally, install the latest version of Python with the following command:
That will install the latest version of Python that is available.
Once the latest version of Python is installed, check it using the following command:
Ensure that the command's output aligns with the version of Python you are in need of.
Well, that's about it. You get to install Python version of your choice on Ubuntu. Enjoy scripting with Python.
Как обновить Python в Linux?
Руководство по обновлению Python в операционных системах семейства Linux.
Введение
Представь себе ситуацию, ты придумал какой-нибудь проект, решил реализовать его на Python, открываешь терминал и обнаруживаешь старую версию, например Python 3.4.
Правильно, обновить Python через пакетный менеджер.
Далее я расскажу как это сделать.
Не забываем самое главное.
Все команды необходимо выполнять под пользователем root или же через sudo.
Обновление Python
Рассмотрим несколько примеров обновления Python в самых популярных дистрибутивах
Обновление Python в Debian Linux (Ubuntu, Raspbian, Mint и другие)
В моем случае я буду использовать raspberrypi 4 с дистрибутивом raspbian (основан на Debian buster). Открываем терминал (или подключаемся по ssh) и вводим команду apt update
Обновление python в дистрибутивах основанных на Debian (Ubuntu и др)
Видим примерно такую же ситуацию, локальный репозиторий обновил информацию о доступным пакетах из сетевого репозитория и стали доступны обновления других пакетов. Но мы сейчас не об этом. Нас интересует только python.
Далее вводим команду
В моем дистрибутиве используется последняя доступная версия 3.7.3-1
Обновление Python в Red Hat Linux (CentOS и Fedora Linux)
В принципе обновление пакетов в linux имеет схожий алгоритм. Сперва вы получаете список доступных пакетов из удаленного репозитория и сравнивание с тем, что установлено у вас локально. После обновление локального репозитория нужно инициализировать установку python. Разнообразных дистрибутивов linux у меня под рукой нет, да и используя я в серверных вариантах только debian-based. Но информация о работе с другими пакетными менеджерами доступна онлайн:)
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
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
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:
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
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
To fix this first remove the current version of python3-apt by running
Then do some cleanup
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
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
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
Now you can install pip by running
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.
You can fix this by reinstalling venv by running
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