Linux update python version

Linux update python version

In order to update python version on the terminal, you can use these commands depending on your operating system:

1#Linux 2 sudo apt update 3 sudo apt install python3.11 4 5 #MacOS 6brew install python

Here is a detailed guide about how to update python version in other operating systems. In this article, we are going to focus on how to install it on the terminal.

Update Python on Windows

To update Python on Windows you should download the Python version you want to upgrade to from python.org. In case you already have installed different Python versions and want to update the version of a virtual environment, you can do it by using the following command:

1python -m venv --upgrade VIRTUAL-ENVIRONMENT-PATH-HERE

To select which Python version we want to use, it’s as simple as as writing py -version-you-want-to-use , example:

1 py -3.8 #selects Python version 3.8 2 py -3.11 # Selects Python version 3.11

Updating Python on Linux

Before getting into upgrading Python, we need to know if it’s already installed (no use to upgrade something that doesn’t exist). To check if Python is installed type the following:

Читайте также:  PHP __DIR__ Demo

If there’s an installed version of Python, the output should show you the installed version like this:

If your computer doesn’t have Python installed, we need first to prepare our system to install Python, so we do the following:

1sudo apt update 2 sudo apt install software-properties-common

Once we have downloaded the necessary files to install Python latest version, we can install it using apt-get (recommended) or using the source code.

Update with Apt-Get

There’s no need to reinvent the wheel, Apt-Get it’s a package manager built in Linux that will make our life easier while installing. As a first step, let’s configure the deadsnakes PPA on the system by running the following command:

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

Python is now updated, but still is pointing to the previously installed version. We need now to update this:

1 sudo update-alternatives --config python3

A list of options will be displayed and prompt to pick the Python version you want to point to, select it by writing the number corresponding to the version you want to use. To verify this selection, write:

Updating Python on MacOs

Updating Python on MacOs is more straight forward. In MacOs systems you can as well have different Python versions installed at the same time. This makes it simpler to update it by visiting python.org MacOs download page, select the installer to download and run it. If you are more of a Homebrew user, run the following commands:

Once the installation finishes, you’ll have the latest Python version installed which you can verify with the following code:

Источник

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

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 upgrade to Python 3.11 on Ubuntu 20.04 and 22.04 LTS

img

In this article, we will upgrade to Python 3.11 and configure it as the default version of Python in Ubuntu 20.04 and 22.04 LTS.

So let’s start with checking the currently installed version of Python on your system.

As seen in the image above, my currently installed Python version is 3.10 but yours may differ.

Install Python 3.11

Follow the simple steps to install and configure Python 3.11

Step 1: Add the repository and update

The latest Python 3.11 is not available in Ubuntu’s default repositories. So, we have to add an additional repository. On launchpad repository named deadsnakes is available for Python Packages.

Add the deadsnakes repository using the below commands.

sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update

Update the package list using the below command.

Verify the updated Python packages list using this command.

As seen in the image above, Now we have Python 3.11 available for installation.

Step 2: Install the Python 3.11 package using apt-get

install Python 3.11 by using the below command :

sudo apt-get install python3.11

Step 3: Add Python 3.10 & Python 3.11 to update-alternatives

Add both old and new versions of Python to Update Alternatives.

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1 sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2

Step 4: Update Python 3 for point to Python 3.11

By default, Python 3 is pointed to Python 3.10. That means when we run python3 it will execute as python 3.10 but we want to execute this as python 3.11.

Type this command to configure python3:

sudo update-alternatives --config python3

You should get the above output. Now type 2 and hit enter for Python 3.11. Remember the selected number may differ so choose the selection number which is for Python 3.11.

Step 5: Test the version of python

Finally, test the current version of Python by typing this :

You should get Python 3.11 as an output.

In this article, we learn how to upgrade Python to the latest version which is 3.11 in Ubuntu 20.04 and 22.04 LTS.

Источник

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