Обновление python через pip linux

Как обновить все пакеты Python установленные с pip

Пакет pip — это программа для установки и управления пакетами Python. Сам пакет pip в репозитории вашего дистрибутива существует в двух версиях:

  • для Python 3 (называется python3-pip или python-pip в зависимости от того, какая версия Python является версией по умолчанию для вашего дистрибутива)
  • для Python 2 (называется python2-pip или python-pip в зависимости от того, какая версия Python является версией по умолчанию для вашего дистрибутива)

С помощью pip можно устанавливать пакеты Python. Это вносит некоторую путаницу, поскольку эти же самые пакеты можно устанавливать из стандартного репозитория вашего дистрибутива. Но в репозитории имеются далеко не все пакеты Python — только те, которые сопроводители дистрибутива упаковали в установочный пакет этого дистрибутива. Следовательно, через pip можно установить намного больше разных пакетов Python (если они вам нужны).

Как обновить пакеты с pip

Но использование pip имеет свои неудобства — программа не отслеживает выход новых версий и не выполняет их автоматическое обновление.

Поэтому пакеты нужно обновлять вручную и по одному следующими командами:

sudo pip install [имя_пакета] --upgrade

Или более короткий вариант:

sudo pip install [имя_пакета] -U

Проблема здесь в том, чтобы узнать вышла ли уже новая версия пакета?

По этой причине лично я стараюсь устанавливать пакеты Python из стандартного репозитория, поскольку в этом случае они обновляются автоматически при обновлении других пакетов системы. И только если их там нет, то я использую для установки pip.

Как с pip показать пакеты, для которых вышли новые версии

С помощью pip можно проверить выход новых версий. К счастью, это для этого не нужно вводить имя каждого пакета по отдельности.

Следующая команда проверяет наличие новых версий для каждого установленного пакета и выведет только те из них, для которых вышли обновления:

Программа проверяет версии для всех пакетов Python. Обычно их довольно много, поэтому программа может работать довольно долго — несколько минут.

Как в pip обновить сразу все пакеты

Можно посмотреть список устаревших пакетов и потом по одному обновлять их командой, которая дана ещё чуть выше. Но это можно сделать проще.

Следующая большая команда найдёт список всех устаревших пакетов Python и обновит их:

for i in $(pip list -o | awk 'NR > 2 '); do sudo pip install -U $i; done

В сердце этой команды лежит предыдущая медленная команда pip list -o, поэтому выполнение займёт определённое время.

Читайте также:  Jupiter notebook для linux

Если вы учитесь программировать на Python3, то вашему сердцу может быть ближе следующий вариант. Создайте файл с именем xx.py и скопируйте в него:

import subprocess as sbp import pip pkgs = eval(str(sbp.run("pip3 list -o --format=json", shell=True, stdout=sbp.PIPE).stdout, encoding='utf-8')) for pkg in pkgs: sbp.run("pip3 install --upgrade " + pkg['name'], shell=True)

Сохраните и закройте этот файл. Когда вы захотите обновить ваши пакеты Python, то запустите этот скрипт следующим образом:

Есть ещё парочка способов выполнить полное обновление системы, пример команды:

sudo pip install -U $(pip freeze | awk '')

Её принцип заключается в том, что она составляет список всех пакетов Python, а затем каждый из них пытается обновить. Если обновления нет — то ничего страшного, просто происходит переход к следующему пакету из списка. Если обновление есть, то оно устанавливается и вновь происходит переход к следующему пакету из списка, пока программа полностью не завершит свою работу.

Конечный результат такой же — будут обновлены все пакеты Python.

У предыдущей команды есть ещё один вариант:

sudo pip install -U $(pip freeze | cut -d '=' -f 1)

Принцип работы абсолютно такой же.

Заключение

pip обновляет пакеты только одной версии Python — то есть для Python3 или для Python2 — это зависит от того, какая версия Python является версией по умолчанию для вашего дистрибутива.

Если вы также хотите обновить пакеты для другой версии, то в предыдущих командах везде заменяйте pip на pip2 или pip3 — в зависимости от вашего дистрибутива.

Или вот вариант ещё проще, следующие команды одинаково сработают абсолютно в любых дистрибутивах, так как в них версии указаны явно (при условии, что pip2 и pip3 установлены в вашей системе).

Для обновления всех пакетов Python3:

for i in $(pip3 list -o | awk 'NR > 2 '); do sudo pip3 install -U $i; done

Для обновления всех пакетов Python2:

for i in $(pip2 list -o | awk 'NR > 3 '); do sudo pip2 install -U $i; done

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

Связанные статьи:

Источник

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.

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

List of content you will read in this article:

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:

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

Method 1: Python update 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.

Step 5: Verify the Version

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

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

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.

Master of word when it comes to technology, internet and privacy. I’m also your usual guy that always aims for the best result and takes a skateboard to work. If you need me, you will find me at the office’s Counter-Strike championships on Fridays or at a.yushkevych@monovm.com

Источник

КАК ОБНОВИТЬ PYTHON ЧЕРЕЗ PIP

Чтобы обновить Python с помощью инструмента управления пакетами pip, необходимо открыть командную строку и ввести следующую команду:

pip install —upgrade python

Данная команда установит последнюю версию Python, доступную в репозитории PyPI, и обновит текущую установленную версию.

Если требуется обновить конкретную версию Python, то следует указать ее номер в конце команды:

pip install —upgrade python=

Например, чтобы обновить Python до версии 3.9.7, следует ввести команду:

pip install —upgrade python=3.9.7

После ввода команды необходимо дождаться завершения процесса обновления. Если в процессе обновления возникнут ошибки, то необходимо проверить наличие необходимых прав доступа и наличие подключения к интернету.

How To Upgrade Pip Version in Python Window — Pip Upgrade Command Windows

Как обновить PIP в Python 3 / mrGURU


How to upgrade all Python packages with pip

Cómo Actualizar PIP En Python (2023) // Actualización De Pip En Python Facil y Rapido

how to upgrade pip in pychram/python.

How To Install PIP in Python 3.11 on Windows 10/11 [ 2023 Update ]

Источник

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