- Updating Python on Ubuntu 20.04 on WSL2
- Steps
- 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 dependencies
- 4.1 Virtual Environments
- Alternatives
- Final Thoughts
- Как обновить python на Ubuntu
- Подготавливаем данные с локальной версии
- Обновляем Ubuntu на сервере
- Обновляем python на сервере
- Меняем версию python в системе «по умолчанию»
- Устанавливаем новое окружение
- Updating Python on Ubuntu 20.04 on WSL2
- Steps
- 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 dependencies
- 4.1 Virtual Environments
- Alternatives
- Final Thoughts
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.
- Check current Python version
- Add deadsnakes PPA and install Python 3.10
- Update Python alias with update-alternatives
- Install pip and other utilities
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.
- Also, I had to use my bash history to find all the commands I ran. ↩︎
- 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. ↩︎
- 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.
Как обновить 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
Устанавливаем новое окружение
Переименовываем старую директорию окружения (мы должны находится в директории сайта с виртуальным окружением):
Затем в этой директории создаем новое виртуальное окружение:
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.
- Check current Python version
- Add deadsnakes PPA and install Python 3.10
- Update Python alias with update-alternatives
- Install pip and other utilities
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.
- Also, I had to use my bash history to find all the commands I ran. ↩︎
- 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. ↩︎
- 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.