Upgrade Python to latest version (3.12) on Ubuntu Linux or WSL2
Ubuntu both Desktop & WSL2 Linux systems come with Python installed by default, but, they are usually not the latest. This is a short guide on how to upgrade your Python to the latest version (Python 3.12) on Ubuntu Linux and solve associated issues.
I am using Ubuntu 22.04 on WSL2, but this should work on any Ubuntu version.
First, check the version of Python installed on your system run
python3 --version
python keyword is used for Python 2.x versions which has been deprecated
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.
Step 1: Check if Python3.12 is available for install
First, update your system by running
sudo apt update sudo apt upgrade -y
sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update
Check if Python 3.12 is available by running
apt list grep python3.12
This will produce the below result, if you see python3.12 it means you can install it
If you see something similar to the above, it means you can install Python 3.12.
Step 2: Install Python 3.12
Now you can install Python 3.12 by running
sudo apt install python3.12
Now though Python 3.12 is installed, if you check the version of your python by running python3 —version you will still see an older version. This is because if you are using Ubuntu Desktop, the default Python is needed by the system and changing it will break your system.
Step 3: Run Python 3.12
You can run Python 3.12 by running
python3.12 --version
The right way to run Python 3.12 On Linux Desktops is by using a virtual environment.
E.g. you can create a new virtual environment by running
python3.12 -m venv env
and activate it by running
env/bin/activate
Now you can run python —version and you should see the latest version of Python as the output.
Extra
If you really, really, really don’t want to type python3.12 every time you want to run a file, you can create an alias.
If you are using bash, run
>> ~/.bashrc >> ~/.bashrc
Or, if you have oh-my-zsh installed, you can avoid typing out python3 by running
>> ~/.zshrc >> ~/.zshrc
After restarting your terminal, you can run your Python apps with py or python .
WSL2 Only: Set Python 3.12 as default
Steps beyond here are tested on WSL2, it may break your Ubuntu/Linux desktop.
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 update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 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.12 is not installed yet.
Fix Python3-apt
Running pip in terminal will not work, as the current pip is not compatible with Python3.12 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
Then do some cleanup
sudo apt autoclean
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.12.
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.12/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.12-distutils
Now you can install pip by running
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py sudo python3.12 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-pip returned non-zero status You can fix this by reinstalling venv by running
sudo apt install python3.12-venv
All should be done now. It is complicated, but this is how you update Python to latest version.
How to update Python in Terminal?
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:
1python3 -version
If there’s an installed version of Python, the output should show you the installed version like this:
1Python 3.11.1
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
Time to update the Apt cache and install the Python package:
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:
1python -version
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:
1brew install python
Once the installation finishes, you’ll have the latest Python version installed which you can verify with the following code:
1python3 --version
Hope you enjoy the reading and keep on the Geek side, you can check the 4Geek’s Blog for more relevant content like how to exit python in terminal.
Обновление Python через терминал
Если у вас уже установлена версия Python, но вы хотите обновить ее до последней версии, выполните команду sudo apt-get upgrade python3 .
- Получить ссылку
- Электронная почта
- Другие приложения
Комментарии
Отправить комментарий
Популярные сообщения
Python как перевести число в другую систему счисления
Преобразуйте числа как профессионал! Узнайте, как Python может перевести любое число в любую систему счисления. Даже если вы никогда раньше не сталкивались с программированием, эта статья поможет вам стать экспертом в считывании двоичных, восьмеричных и шестнадцатеричных чисел. Не пропустите возможность раскрыть секреты произвольной системы счисления в Python! Python: Перевод числа в другую систему счисления В языке программирования Python преобразование числа в другую систему счисления может быть выполнено с использованием встроенных функций и методов. Преобразование чисел в двоичную систему Python предоставляет встроенную функцию bin() для преобразования числа в двоичную систему. # Пример преобразования числа в двоичную систему num = 18 binary_num = bin(num) print(binary_num) # Вывод: 0b10010 Преобразование чисел в восьмеричную систему Функция oct() в Python преобразует число в восьмеричную систему. # Пример преобразования числа в восьмеричную систему num = 18
Python какие игры написаны
Невероятно! Узнайте, как Python трансформирует игровую индустрию и какие популярные игры были созданы с его помощью! Мир бронетехники, космические исследования и рок-гитара — все это и многое другое в нашей свежей статье! Python: Игры, написанные на этом языке Python — это мощный и гибкий язык программирования, который используется во множестве областей, включая разработку игр. В этой статье мы рассмотрим некоторые игры, написанные на Python. World of Tanks World of Tanks — это многопользовательская онлайн-игра, посвященная бронетехнике середины XX века. Игра разработана белорусской компанией Wargaming. В основе движка игры лежит Python, который используется для скриптов и алгоритмов AI. Battlefield 2 Battlefield 2 — это популярная игра в жанре шутер от первого лица, разработанная шведской компанией DICE. В игре Python использовался для написания логики сервера и различных модов. Eve Online Eve Online — это многопользовательская он
Python seaborn корреляционная матрица
Секреты Python Seaborn: Взрывная Корреляционная Матрица! Ваш путь к мастерству анализа данных!» Python Seaborn Корреляционная Матрица Корреляционная матрица — это важный инструмент для анализа данных и выявления взаимосвязей между переменными. В Python, библиотека Seaborn предоставляет удобные средства для визуализации корреляционных матриц. Для начала, мы импортируем необходимые библиотеки: import seaborn as sns import matplotlib.pyplot as plt Далее, мы загружаем наши данные и создаем корреляционную матрицу: # Загрузка данных data = sns.load_dataset(«iris») # Создание корреляционной матрицы corr_matrix = data.corr() Теперь мы можем визуализировать корреляционную матрицу с помощью Seaborn: # Создание тепловой карты корреляционной матрицы plt.figure(figsize=(8, 6)) sns.heatmap(corr_matrix, annot=True, cmap=»coolwarm», linewidths=.5) plt.title(«Кор
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:
python3 --version
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:
Command 'python' not found
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:
$ python3 --version Python 3.10.4
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:
$ python3 --version python3: command not found
![]()
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:
sudo apt update sudo apt install python3
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:
sudo apt install software-properties-common
Once the apt repositories manager package is installed, we can now easily add the Deadsnakes PPA. The command to do so is given below:
sudo add-apt-repository ppa:deadsnakes/ppa
The PPA is added. Now we need to update the local package list.
sudo apt update
Finally, install the latest version of Python with the following command:
sudo apt install python3
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:
python3 --version
Ensure that the command’s output aligns with the version of Python you are in need of.
Well, that’s about it. If you have Conda on Ubuntu, you are fine. But if you use Anaconda, upgrading Python version becomes important. Enjoy scripting with Python.