Ubuntu server обновить python

Updating Python on Ubuntu 20.04 on WSL2

Want to update Python to a newer version on WSL2? Here’s one way.

Ubuntu on WSL2 currently comes loaded with Python v3.8, which is the default in Ubuntu 20.04. I wanted to update to Python v3.10, as I try to use more recent software releases when starting new projects. Updating Python took more work than I thought it would (I’m more familiar with Node and utilizing node version manager to manage Node versions). Eventually I did get it all worked out, and in an effort to remember what I did, I’m writing this post to jot down the steps. [1]

Please be aware that I’m not fully up-to-date on current Python practices. Chances are these steps may not be best methods, but it worked for me.

Steps

All instructions assume you’re running them in a WSL2 terminal, not a Windows host terminal.

  1. Check current Python version
  2. Add deadsnakes PPA and install Python 3.10
  3. Update Python alias with update-alternatives
  4. Install pip and other utilities
Читайте также:  Генерация номера телефона java

1. Check current Python version

It’s always good to know what you already have so we can check by running a couple commands

Version 3.8.10 is the current Python version when running vanilla, up-to-date Ubuntu 20.04 in WSL2. If this returns a version greater than 3.8.10, congrats, you’re done!

You can see where it’s loading python3 from by

You must use python3 as the Python command, as python is not installed in Ubuntu by default. [2]

2. Add deadsnakes PPA and install Python 3.10

The official method to install different version of Python is by downloading the source code and compiling it yourself. Rather than go through that, deadsnakes has created a PPA that contains recent versions of Python compiled for Ubuntu.

To add this PPA to your system run

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

Once added, you can now install Python 3.10 by running

sudo apt install python3.10 python3.10 --version #Python 3.10.4 which python3.10 #/usr/bin/python3.10 

3. Update Python alias with update-alternatives

Since you can have multiple versions of Python installed side-by-side, it’s important to preface all Python commands by specifying the specific version. By default, calling python3 will use still use Python 3.8.10. If you want to use 3.10, you’ll always have to call python3.10 .

Notice also that calling python will still give a command not found message.

Ubuntu has a package called update-alternatives that can manage calling different versions of packages and have them share a common command. In this case, we want to be able to just use python to reference 3.10.4. You can do so by running

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

Now when you run python —version you should get Python 3.10.4 . [3]

4. Install pip and other dependencies

To finish up, there’s a few other Python tools necessary for development. You’ll need pip for package management, venv for virtual environments, and a couple other tools:

sudo apt install python3-pip python3.10-pip python3.10-venv python3.10-distutils curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10 source ~/.bashrc pip --version 

4.1 Virtual Environments

I always use a virtual environment when I do any Python project. You never know if you’ll need to use a package not included in the standard library. Since we just installed a compatible version of venv , we can create a virtual environment in our project’s root directory and activate it by

python -m venv venv source venv/bin/activate 

I usually also make sure the latest version of pip is installed in the virtual environment and can do so by

Alternatives

There is pyenv that can perform similarly to node version manager. I did try to install this at one point a while ago, but I messed something up. I do think it’d be worthwhile to check out and try again in the future.

Final Thoughts

By no means am I a Python expert, but I wanted to jot down how I managed to update to a newer version of Python in WSL2. Hopefully these steps will at least point you in the right direction. Just to reiterate, there is most definitely a better method of doing this, but I got my system working well enough for me. If you know of a better way, drop me a line.

  1. Also, I had to use my bash history to find all the commands I ran. ↩︎
  2. Yes this confusing. There is a package called python-is-python3 that you can install from apt should you desire, but step 3 in this guide shows how to specify alternates. ↩︎
  3. I’m not 100% sure that setting alternatives won’t break something elsewhere in your system. If you’d rather not deal with it, just skip this step and be sure to always use the python3.10 command. ↩︎

This post is licensed under CC BY 4.0 by the author. The source for this page is available on GitHub.

Источник

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

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

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

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

Источник

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