Как обновить питон линукс

How to update python to latest version and set as default

I am currently on ubuntu 18.04. My default python version is Python 3.7.9 I wanted to upgrade it to Python 3.9.2 and set it as default python version How do I do that ?

if you don’t have it in apt then you can add special repo for Ubuntu deadsnakes Python repo for Ubuntu . And after adding repo you should have all versions in apt

2 Answers 2

Install Python normally with the deadsnake PPA:

sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.9 

Check if you can access Python:

If so, create a symlink to set it as «default»:

sudo mv /usr/bin/python /usr/bin/python3.7 sudo ln -s $(which python3.9) /usr/bin/python 

This is the error I am getting E: Unable to locate package python3.9 E: Couldn’t find any package by glob ‘python3.9’

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

sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt install python3.9 

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

This repo works also in Linux Mint which is based on Ubuntu.

Источник

Как обновить python на Ubuntu

Admin 30.10.2022 Linux, Python, Ubuntu

Обновление на новые версии это всегда «весело». Вместе с новым функционалом понадобится убрать устаревшие функции, обновить потерявшие совместимость модули и в целом проделать большую работу.

Читайте также:  Linux virtual windows server

Подготавливаем данные с локальной версии

Сначала обновляем версию локально, тестируем. Фиксируем изменения всех зависимостей командой:

Обновляем 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

Устанавливаем новое окружение

Переименовываем старую директорию окружения (мы должны находится в директории сайта с виртуальным окружением):

Затем в этой директории создаем новое виртуальное окружение:

Источник

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

  1. Update Python to the latest version
  2. Fix pip & other Python related issues
  3. 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

Читайте также:  Linux list all dev

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 в Linux?

Как обновить 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.

Как обновить Python в Linux?

В моем дистрибутиве используется последняя доступная версия 3.7.3-1

Обновление Python в Red Hat Linux (CentOS и Fedora Linux)

В принципе обновление пакетов в linux имеет схожий алгоритм. Сперва вы получаете список доступных пакетов из удаленного репозитория и сравнивание с тем, что установлено у вас локально. После обновление локального репозитория нужно инициализировать установку python. Разнообразных дистрибутивов linux у меня под рукой нет, да и используя я в серверных вариантах только debian-based. Но информация о работе с другими пакетными менеджерами доступна онлайн:)

Обновление python выполняется одной командой

Заключение

В этом руководстве мы узнали как обновить Python в Linux.

Источник

Оцените статью
Adblock
detector