Как обновить python в ubuntu
Перейти к содержимому

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

  • автор:

How to Upgrade Python to 3.9

Every fresh Python release comes with bug fixes and new features. Python 3.9, the latest point release at the time of writing, comes with features such as improved time zone support, dictionary updates, and more flexible decorators.

This tutorial shows you how to upgrade Python to version 3.9 on all the major operating systems — Windows, macOS, and Linux.

How to Upgrade Python to 3.9

  • Administrative rights on the operating system you are using.
  • Knowledge of which Python version is currently on your system. If you need help finding out the version of your Python installation, check out How to Check Python Version.

Note: If you are upgrading from a Python 2 release and do not have Python 3 installed, read our comprehensive guides on how to install it on:

Upgrading Python on Windows OS

To upgrade Python on Windows, download the installer or search for the app in the Microsoft Store.

Upgrade to Python 3 with the Installer

1. In your browser, visit the Python Releases for Windows section on the official Python website.

2. Click the Download Python button to download the installation file on your computer.

Downloading the newest version of Python for Windows

3. Next, run the Python installer. If you are upgrading from another point release of Python 3 (for example, 3.8.10), the installer suggests to install Python 3.9. Select Install Now to install Python with recommended options, or select Customize Installation to pick the install location and features.

Starting installation of Python 3 in Windows

If you already have an older version of the same Python release (for example, 3.9.1), the installer offers to upgrade your Python installation. Proceed by selecting Upgrade Now.

Starting the upgrade of Python 3 in Windows

4. When the installation finishes, check whether the new version of Python has been installed successfully. Open Windows PowerShell and type:

The output should show the latest version of Python, as in the image below.

Confirming the successful Python 3 installation in Windows

Install Python 3.9 from the Microsoft Store

If you want to use Python 3.9 to learn the basics or test some simple concepts, find and install the Python 3.9 app from the Microsoft Store.

1. Go to Microsoft Store and type Python in the search field.

2. Select Python 3.9 from the search results that appear.

Searching for Python 3 in Microsoft Store

3. Click the Get button to start the installation.

Starting Python 3.9 installation in Microsoft Store

Start the interactive Python 3.9 experience by finding the app in the Start Menu.

Upgrading Python on macOS

On macOS, Python can be installed, upgraded, and maintained using the command line interface or the GUI.

Upgrade Python using Homebrew

Install Python in the macOS terminal using the Homebrew package manager. If you do not have Homebrew, install it by typing the following script in the terminal:

Then, proceed with the steps:

1. Update Homebrew by running:

2. If you are upgrading from Python 2, install Python 3 with the command:

If you already have a version of Python 3 installed, upgrade the package with the brew upgrade command:

Upgrade Python with the Installer

1. In your browser, navigate to the Python Releases for macOS page, on Python’s official website.

2. Click the link to download the latest Python 3 release on your computer.

Downloading the Python installer for macOS from the official website

3. Run the installer. Go through the installation steps by clicking Continue, agreeing to the License, and confirming the installation location and type.

Starting a Python 3.9 installation in Mac OS using the installer

4. Once the installation is complete, select Close.

The installer confirms the successful installation of Python 3.9 on MacOS

5. Finally, confirm that the new Python version has been successfully installed by typing the following in terminal:

The output should display the latest version of Python.

Checking the Python version in macOS

Upgrading Python in Linux

This article uses Ubuntu and its APT package manager to upgrade Python. If you are using a different Linux distribution, replace the apt Linux command with the appropriate command featured for your package manager.

Warning: Many Linux systems have Python 2 installed as the system version. Removing Python 2 could cause a system error. If you are planning to install Python 3 on Linux, install it alongside Python 2 and invoke it with the python3 command.

1. Start by updating the repositories:

2. Next, install Python 3.9 by running:

When prompted, type Y to start the installation.

Installing Python 3.9 in Ubuntu with apt

3. Once Python installs, invoke the 3.9 version by running:

4. However, checking the installation with the python3 —version command still returns the old version. To fix this, you need to create a list of update alternatives. First, add the old version to the list with the command:

5. Now add the new version:

Adding Python 3.9 to update alternatives

6. Next, type the following command to configure the priority status of the versions:

The output displays the available choices and their assigned number (in the example below, the numbers are 0, 1, 2). Type the number of the the version you wish to use and press Enter.

Configuring update-alternatives for Python 3 in Ubuntu

7. If you are not planning to use the old version of Python, remove the symlink that contained the previous Python 3 version with:

8. Then, replace the symlink with the new version:

9. Now, check the default version:

The output should confirm the successful installation and setup of the latest available version.

Confirming the successful change of Python 3 version in Ubuntu

Why Should You Upgrade Python?

Since Python 3 was not a backward-compatible release, for a long time Python 2 remained the version of choice for those who wanted a stable development environment. Some services like Google App Engine did not support Python 3 for a long time.

However, given that the official support for the final Python 2.7 release has ended, upgrading to Python 3 is now strongly recommended. Python 3 is faster, and its syntax is more user-friendly.

If you already work with Python 3, upgrading to the latest point release gives you all the security updates and bug fixes.

After reading this tutorial, you should know how to upgrade your Python 3 version on Windows, macOS, and Linux. If you want to learn more about Python, read our article on Python data types.

How to Update Python Version? — [Upgrade Python Version]

Are you looking to update Python version to the latest python version? Then this blog post will guide you with how to upgrade Python version.

List of content you will read in this article:

  • 1. What is PIP?
  • 2. How to update Python on Windows Operating System?
  • 3. How To Upgrade Python on macOS?
  • 4. How to Update Python version on LINUX?
  • 5. Conclusion

Python is an open-source high-level programming language that allows users to execute commands, plugins on their machine, and even software from several major suppliers. It means you can operate it on many different operating systems, including the Windows VPS Server. Python is a cross-platform programing language.

Pip is one of the best applications for Python package installation and administration. Pip’s popularity stems from the many apps that use this tool. Pip enables 3rd Party package installed to manage binary packages with the quickly configured package manager. Since Python’s latest releases have piping as normal, this guide will explain how to install PIP and how to update Python version with a complete step-by-step guide.

What is PIP?

PIP is a software management framework for installing and managing Python-written program packages. It is called the ‘preferred software installer’ or ‘Pip Installs Packages.’ PIP, used for Python, is a command-line interface for handling PyPI program installation. You might need to upgrade PIP if you’re using an earlier version of Python on Windows. Download the application file, open the command- line and start the installer to run PIP on Windows quickly. It will teach you how PIP is installed on Windows and how it can be modified, upgraded, and set up.

How to update Python on Windows Operating System?

There are two simple ways to update your current Python version with the latest one. They are as follows:

  1. Using the Python Installer
  2. Using the Windows Chocolatey Package Manager

So let’s see how we can update the Python version with these two methods, one by one.

Method 1: Update the Version of Python on Windows using the Python Installer

This method of updating the Python version will work if Python is installed or not on your System.

If Python is already installed on your system, you can check it using the python -V command.

Step 1: Download the Python installer from the Official Website of Python

The easiest way to update the Python version is to download the latest version from the official website ( https://www.python.org/downloads/ )

You can click on the Download Python 3.11.0 button, and it will download the latest compatible Python version for your system.

Step 2: Install the Downloaded Python Installer

After downloading the exe file, double-click on it to install Python.

Step 3: Install Python

Now, you can install the latest version of Python.

Check the “Add python.ext to PATH”, then click on the “ Install Now ” button.

This will start the installation process.

After processing, the latest version of Python will be installed on your system.

Click on the “Close” Button.

Step 4: Verify the Update

After successful installation, you can verify whether or not the latest version is installed on your system. To check the version, you can again run the same command, python -V , on the prompt command.

Now, you can see that it is showing the latest installed version, i.e., Python 3.11.0.

Note: If it still shows the old version, you may restart your system . Or uninstall the old version from the control panel .

Method 2: Install Python using Command Line Only using the Chocolatey Package Manager

Chocolatey is a Package Manager command line tool for windows, and we can use it to install software for our window system. In our case, we can use it to install Python or update the current version of Python.

Step 1 Open The Powershell as Administrator

To install Chocolatey, you need to open PowerShell as Administrator.

Step 2: Install the Chocolatey Package Manager Command

Now, you can install the Chocolatey package manager using the following command.

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString(‘https://community.chocolatey.org/install.ps1’))

Step 3: Verify the Chocolatey Installation

Now, you need to check whether Chocolatey has been installed successfully. To check it, run the “ choco ” command.

It is installed successfully because it is showing version Chocolatey v1.2.0.

Step 4: Update Python with Chocolatey

With the help of the choco upgrade command, we can update our current Python version.

choco upgrade python -y

Step 5: Verify the Version

You can again check the latest installed Python version using the following command.

python -V

Note: The old version of Python will remain on your system. You can uninstall the old version from the control panel.

How To Upgrade Python on macOS?

You can download the latest version of Python for macOS from the official Python website, similar to what you did on windows OS to update Python version on your system. To check whether it is updated to the lasted version or not, follow the below-listed commands to check the Python version.

If you want to execute this new Python release with the python command instead of python3, install an alias in your $HOME directory’s bash profile file.

Open the terminal window and type the following commands:

$ cd $HOME
$ nano .bash_profile

Then, at the bottom, add this segment.

Python 3.9 version can be checked using the following command.

How to Update Python version on LINUX?

Users can use the below listed Linux commands to upgrade Python version on the Linux server:

ppa:deadsnakes/ppa can be added to the system’s Software Sources to upgrade the machine with unsupported packages from this untrusted PPA.

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

This command is used to update the Python package.

$ sudo apt update
$ sudo apt install python3.9

Then, using the commands below, you can search the versions of your new and current Python installations:

This command will show you the following version of python installed in your system

$ sudo python —version

$ sudo python3 —version

$ sudo python3.9 —version

Conclusion

We have seen how to update Python version on operating systems like Windows, Mac OS, and Linux. Follow the guide carefully to update your python software. We believe this guide fulfills your requirement though you can install the latest version successfully. Leave your comments below for your feedback and queries.

People Are Also Reading:

Tutorials

What is the latest python version?

Python is a programming language with many features and libraries that can be used for various purposes. The latest version of Python is 3.11.0, which was released on Oct. 24, 2022. This version includes bug fixes and improvements to the standard library.

Управление несколькими версиями Python под управлением Ubuntu 20.04

Одно из моих первых разочарований при разработке на Python не имело ничего общего с самим Python, а скорее с излишне изотерическими действиями по развертыванию приложений на Python. Учебные курсы и руководства отлично справляются с задачей обучения студентов запуску Python кода локально, но действительно стоящие приложения не запускают на локальных машинах: они работают на интернет серверах потому что именно в этом и есть их назначение, не так ли? Хотя может быть я высказал сумасшедшую идею.

Ubuntu 20.04 это первая LTS версия Ubuntu в которой отсутствует Python2 и которая поставляется из коробки с установленной версией Python 3.8.5. Но что если написанное вами приложение использующее более новую версию Python? Если вы, как и я, пытались заменить установленную по умолчанию в системе версию, то в процессе сломали вашу ОС. Если до этого вам никто не говорил не делать этого, тогда я возьму на себя эту честь: не делайте этого.

Итак, что же нам делать? Существует нескольок путей как обновить версию Python на Ubuntu, но использование вастроенного в Ubuntu’s механизма «alternative install» оптимально по нескольким причинам:

Мы хотим оставить нетронутойси стемную версию Python

По возможности не возиться с Python PATH

Мы можем удобно переключать активную версию Python с использованием CLI

Мы пройдемся по способу легкой и безопасной установки последней версии Python не затрагивая системную версию Python.

Скачивание последней версии Python

Первый шаг должен быть вам знаком: нам необходимо обновить зеркала Ubuntu и установленные пакеты, что бы быть уверенными что мы загружаем последние версии пакетов при установке чего-либо:

Установка другой версии Python на Ubuntu трубует установки целого ряда зависимых библиотек для Python. Я честно гвооря не уверен что делает половина из этого, и скорее всего это никому из нас никогда не понадобится. Но поверьте, это необходимый шаг:

Именно здесь многие могут начать установку Python с помощью Ubuntu package manager командой apt-get install python3.X. Мы скачаем и соберем последнюю версию Python из исходные кодов по нескольким причинам. Если версия Python достаточно свежая, некоторые машины под управлением Ubuntu могут не иметь обновленных зеркал что бы получить последнюю версию, но важнее всего то, что этот способ позволяет упростить управление несколькими версиями Python на Ubuntu.

Последнюю версию Python всегда можно найти на официальной странице с релизами на Python.org:

Первая ссылка на указанной странице должна называться Latest Python 3 Release — Python 3.X. Перейдя по ней необходимо прокрутить вниз страницы до секции «Files» и скопировать URL ссылки Gzipped source tarball.

На вашей Ubuntu машине необходимо теперь скачать эти исходные коды с помощью утилиты «wget». Ниже пример команд для скачивания заархивированной версии Python 3.9.2 в папку /opt и распаковка ее:

Теперь последняя версия Python скачана. После этого нам остается ее установить… правильно.

Установка альтернативной версии Python из исходных кодов

Главное разочарование установки Python с использованием команды apt-get install python3.X это что Python будет установлен нормально, но Ubuntu будет по прежнему использовать установленную в системе по умолчанию версию Python. К счастью для нас Ubuntu позволяет устанавливать нам дополнительные (альтернативные) версии Python с использованием команды make altinstall :

Исполнение этих команд может занять некоторое время. После того, как команды будут выполнены вы можете увидеть python3.9 в вашей директории /usr/local/bin/ :

Итак, теперь у нас есть две установленные версии Python: установленная в системе по-умолчанию Python 3.8.5 и добавленная нами новая версия Python 3.9.2. Мы хотим оставить нетронутой установленную в системе версию по-умолчанию, но мы так же хотим запускать написанные нами приложения в версии Python 3.9… итак как мы можем этим управлять?

Linux предусматривает такой сценарий с помощью команды update-alternatives . Мы можем сказать Ubuntu что у нас есть ветка с альтернативной версией на нашей машине, это предоставит нам возможность легко переключаться между ними. Вот как это работает:

Мы запускаем update-alternatives дважды: один раз для Python 3.8, и один раз для Python 3.9. Теперь мы можем использовать команду update-alternatives —list что бы посмотреть все альтернативные версии какого-либо установленного ПО:

Теперь мы можем переключаться между установленными версиями Python! Запустите следующую команду:

После выполнения команды вы должны получить подсказку как в приведенном ниже примере. Это будет список всех доступных версий Python в вашей системе. Выберите версию которую хотите использовать введя соответствующий номер версии указанный в колонке Selection :

И вы это сделали! Для переключения версии Python все что нужно — это ввести запрошенный номер версии Python указанный в колонке selection .

Это прозвучит абсурдно, но изменить версию Python в Ubuntu ничего не сломав — это впечатляет. Я бы сказал что это в основном вина тех, кто преподаает Python. Если «учат те, кто не может сделать», то было бы логично предположить что Python преподают те, кто не запустил ни одного значимого проекта. Это было жестко, но не бейте меня нисмотря ни на что.

Мы закончили самую трудную часть, но осталось еще немного рутинной работы. Нам все еще нужно установить pip для нашей свежеустановленной версии Python, а так же обновить pip до последней версии.

Вы наверняка заметили что Ubuntu 20.04 (и новее) заставляют нас явно указывать python3 при использовании Python несмотря на отсутствие Python 2 на машине. Это немного раздражает, но так же потенциально может сломать библиотеки которые пытаются использовать Python (NPM, sqlite и node-qyp например)

Возможно вы чувствуетет в себе достаточно сил что бы создать alias, который будет при обращении к python ссылаться на python3, но к сожалению это не будет работать так, как вам бы хотелось. Хорошая новость в том, что есть простое решение:

Да, есть целый пакет для Ubuntu созданный специально для решения этой задачи. Но это работает ¯_(ツ)_/¯.

How to Update Python on Ubuntu?

First of all, you want to open the Ubuntu 20.04 shell terminal application on Ubuntu 20.04 desktop. For that, you have to utilize the everlasting shortcut key “Ctrl+Alt+T” on the desktop of Ubuntu 20.04.

The shell application will be opened. Now, you have to check the version of a Python language already installed on your system. For this, you will be executing a version command of Ubuntu 20.04 with the keyword python. The command has been shown in the attached screenshot of the terminal. It clearly shows that any version of Python language is not configured in our system and we need to install it by ourselves. Many commands can be used.

So, we have to install the python version on our system supported by Ubuntu 20.04. Before that, we have to update our system. The apt package will be utilized in the update command to do so. The command is displayed in the image as well. The execution of this apt command leads us to enter the sudo password of our system. After adding the password, our system will update itself and its packages. The command and the process have been shown in the image.

It’s time to install the python old version on our system first. This is necessary to be done because we have to then update the python to the newest version after that. We have been installing Python version 2 on our system using the apt installation command displayed below.

After making the package ready, it will pause the process of installation for a while to ask us to affirm our action. It will let us know that 16.5 MB of space will be occupied by this package and if we want to continue installing it. So, we tapped “Y” to continue the installation process.

The installation process will start progressing. After it reaches 100 percent, it will be completed. Let’s just update the Linux system once again with the “apt” package.

After the successful installation of Python, we will be checking the version of python that has been installed. The version command has been used here once again as illustrated from the image below. We have used the “python2” keyword to check the installed version of Python 2.

When we have checked for the Python 3 versions on your system, it shows that the Python 3.8.2 version has also been installed with Python 2. While Python has come up with the Python 3.9 version as well. So, we need to upgrade this latest version to Ubuntu 20.04.

Let’s begin with the update of Python 3. First of all, you need to install all the required packages and repositories that are prerequisites for Python 3.9. Instead of listing all packages in the installation command, we have to just use the keyword “software-properties-common” in the instruction. We have done it in the command and the process has been started.

It will also pause the installation of required packages to affirm your action. It’s been informed that this process will take 14.3 kb of space on your system and do you want to continue it. So, we have added “y” and tapped the “Enter” button to start the process of installation.

The packages will be installed and configured on our system one by one and may take up to 5 minutes. The completion of this process has been shown in the small image below.

Before the installation of Python 3.9, you must have to add the “ppa” repository to your system. Without “ppa”, you will be unable to install Python 3.9. You need to use the “add-apt-repository” command of an apt package to do so. You have to use the “ppa:deadsnakes/ppa” keyword within your command with sudo privileges. Execute the command shown in the image below and it will set your system for new Python versions.

After a few seconds, the process of adding ppa will ask you to press the Enter button to start adding ppa requirements and packages i.e., prerequisites. we pressed Enter and the system installed the ppa package on our system. The output is shown in the attached photo.

Now, we cannot use the simple apt installation command with the keyword “python3.9” to install the latest python version. We have to install the Python environment variables and development interface with the keywords “python3.9-venv” and “python3.9-dev” as below.

Again, the system has been asking to tap “y” to affirm the action of installation as it takes 114 MB space on our Ubuntu system. We have tapped “y” and pressed the “Enter” key to continue.

The system has started upgrading the python. The process will take some to complete as it will also install the development environment along with the environment variables of Python 3.9.

After the complete installation, we have utilized it to check the Python version. We have found that the Python 3.9 latest version is now configured on our Ubuntu 20.04 system fully.

Conclusion

This article contains all the information and process regarding the update of Python in the Ubuntu 20.04 system. We have started from the very basics by installing the old version of Python on our system i.e., python2. Then, we have shown the way to update the Python version and upgrade it to version 3.9 by utilizing some commands. We hope you liked this article.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *