How to Update all Python Packages with a Single pip Command
Ensure all present Python packages on Windows and Linux systems are parallel with their latest available versions from the command line.
With Python, the best practice of pinning all the packages in an environment at a specific version ensures that the environment can be reproduced months or even years later.
- Pinned packages in a requirements.txt file are denoted by == . For example, requests==2.21.0 . Pinned packages should never be updated except for a very good reason, such as to fix a critical bug or vulnerability.
- Conversely, unpinned packages are typically denoted by >= , which indicates that the package can be replaced by a later version. Unpinned packages are more common in development environments, where the latest version can offer bug fixes, security patches and even new functionality.
As packages age, many of them are likely to have vulnerabilities and bugs logged against them. In order to maintain the security and performance of your application, you’ll need to update these packages to a newer version that fixes the issue.
The pip package manager can be used to update one or more packages system-wide. However, if your deployment is located in a virtual environment, you should use the Pipenv package manager to update all Python packages.
NOTE: be aware that upgrading packages can break your environment by installing incompatible dependencies. This is because pip and pipenv do not resolve dependencies.
Python Package Upgrade Checklist
In general, you can use the following steps to perform a package upgrade:
- Check that Python is installed
Before packages can be updated, ensure that a Python installation containing the necessary files needed for updating packages is in place by following the steps outlined in “[Using Python on Windows]” in the official documentation.
2. Get a list of all the outdated packages
To generate a list of all outdated packages:
3. Upgrade outdated packages
Depending on your operating system or virtual environment, refer to the following sections.
The easiest way to update all packages in a Windows environment is to use pip in conjunction with Windows PowerShell:
- Open a command shell by typing powershell in the Search Box of the Task bar
- Enter:
This will upgrade all packages system-wide to the latest version available in the Python Package Index (PyPI).
Update all Python Packages on Linux
Linux provides a number of ways to use pip in order to upgrade Python packages, including grep and awk.
To upgrade all packages using pip with grep on Ubuntu Linux:
To upgrade all packages using pip with awk on Ubuntu Linux:
Updating Python Packages on Windows or Linux
Pip can be used to upgrade all packages on either Windows or Linux:
- Output a list of installed packages into a requirements file (requirements.txt):
- Edit requirements.txt, and replace all == with >= . Use the Replace All command in the editor.
- Upgrade all outdated packages:
Updating all Packages in a Virtual Environment
The easiest way to update unpinned packages (i.e., packages that do not require a specific version) in a virtual environment is to run the following Python script that makes use of pip:
Updating all Packages in a Pipenv Environment
The simplest way to update all the unpinned packages in a specific virtual environment created with pipenv is to do the following steps:
Как обновить все пакеты 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 имеет свои неудобства — программа не отслеживает выход новых версий и не выполняет их автоматическое обновление.
Поэтому пакеты нужно обновлять вручную и по одному следующими командами:
Или более короткий вариант:
Проблема здесь в том, чтобы узнать вышла ли уже новая версия пакета?
По этой причине лично я стараюсь устанавливать пакеты Python из стандартного репозитория, поскольку в этом случае они обновляются автоматически при обновлении других пакетов системы. И только если их там нет, то я использую для установки pip.
Как с pip показать пакеты, для которых вышли новые версии
С помощью pip можно проверить выход новых версий. К счастью, это для этого не нужно вводить имя каждого пакета по отдельности.
Следующая команда проверяет наличие новых версий для каждого установленного пакета и выведет только те из них, для которых вышли обновления:
Вариант для Python3:
Вариант для Python2:
Программа проверяет версии для всех пакетов Python. Обычно их довольно много, поэтому программа может работать довольно долго — несколько минут.
Как в pip обновить сразу все пакеты
Можно посмотреть список устаревших пакетов и потом по одному обновлять их командой, которая дана ещё чуть выше. Но это можно сделать проще.
Следующая большая команда найдёт список всех устаревших пакетов Python и обновит их:
В сердце этой команды лежит предыдущая медленная команда pip list -o, поэтому выполнение займёт определённое время.
Если вы учитесь программировать на Python3, то вашему сердцу может быть ближе следующий вариант. Создайте файл с именем xx.py и скопируйте в него:
Сохраните и закройте этот файл. Когда вы захотите обновить ваши пакеты Python, то запустите этот скрипт следующим образом:
Есть ещё парочка способов выполнить полное обновление системы, пример команды:
Её принцип заключается в том, что она составляет список всех пакетов Python, а затем каждый из них пытается обновить. Если обновления нет — то ничего страшного, просто происходит переход к следующему пакету из списка. Если обновление есть, то оно устанавливается и вновь происходит переход к следующему пакету из списка, пока программа полностью не завершит свою работу.
Конечный результат такой же — будут обновлены все пакеты Python.
У предыдущей команды есть ещё один вариант:
Принцип работы абсолютно такой же.
Заключение
pip обновляет пакеты только одной версии Python — то есть для Python3 или для Python2 — это зависит от того, какая версия Python является версией по умолчанию для вашего дистрибутива.
Если вы также хотите обновить пакеты для другой версии, то в предыдущих командах везде заменяйте pip на pip2 или pip3 — в зависимости от вашего дистрибутива.
Или вот вариант ещё проще, следующие команды одинаково сработают абсолютно в любых дистрибутивах, так как в них версии указаны явно (при условии, что pip2 и pip3 установлены в вашей системе).
Для обновления всех пакетов Python3:
Для обновления всех пакетов Python2:
При обновлении пакетов могут возникать различные ошибки и предупреждения, которые требуют индивидуального подхода. Например, если ошибка в отсутствующей зависимости, то установите необходимую зависимость для обновлённого пакета.
How to update/upgrade a package using pip?
What is the way to update a package using pip? those do not work:
I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn’t pop up and other questions from stack overflow are relevant but are not exactly about that)
9 Answers 9
Using sudo will ask to enter your root password to confirm the action, but although common, is considered unsafe.
If you do not have a root password (if you are not the admin) you should probably work with virtualenv.
You can also use the user flag to install it on this user only.
For a non-specific package and a more general solution, you can check out pip-review. A tool that checks what packages could/should be updated.
![]()
Use this code in terminal:
For example I want update pip package:
![]()
![]()
tl;dr script to update all installed packages
If you only want to upgrade one package, refer to @borgr’s answer. I often find it necessary, or at least pleasing, to upgrade all my packages at once. Currently, pip doesn’t natively support that action, but with sh scripting it is simple enough. You use pip list , awk (or cut and tail ), and command substitution. My normal one-liner is:
This will ask for the root password. If you do not have access to that, the —user option of pip or virtualenv may be something to look into.
How To Update/Upgrade A Python Package with Pip?
Python provides the Pip or Python Package Index which is used to add useful extra modules to the Python. The pip is command is provided to search, install, update, and remove the modules provided by the Python Package Index. One of the most popular use cases for pip command is updating existing and already installed Python packages. In this tutorial, we will examine different cases for update and upgrade Python packages.
List Installed Python Packages with Pip
Before updating any package the best practice is listing installed packages. The pip command provides the list parameter which will list installed packages. Also version information about the installed packages will be provided. pip is used for the Python2 and pip3 is used for the Python3.
The following output will be provided with the package names and version information.
Check If Specified Python Package Is Installated with Pip
As the list parameter lists installed pip packages with their version information we can also check for the specific package by using an external command like grep. We will provide the package name we want to check and list. In the following example, we will check for different packages. If the package is not installed there will be no output. We can also provide only some part of the package name and all matched packages will be listed below.

List Outdated Python Packages
Python is a dynamic programming language and the modules provided by Pip updated regularly. Especially popular packages and projects get more frequent updates. After installing a package it will be outdated and should be updated. The pip command provides the list —outdate parameter which will list only outdated packages. This command will connect to the Pip repositories and collects installed packages information. It may take some time as all installed packages will be queried from the Pip repository.
From the output we can see that the installed version of the package and most recent version provided by the Pip is listed for every package.
Update/Upgrade Python Package To The Latest Version with Pip
Now we have learned every step before updating or upgrade a Python package with pip. By the way, both terms update and upgrade can be used for an update package but the pip command uses the install –user –upgrade parameter to update the package. In the following example, we will update a specific package named lxml .

Update/Upgrade Python Package To Specific Version with Pip
By default, the specified package will be updated or upgraded to the latest version. But this can be a problem if we need a specific version of the Python package. This generally occurs where some software depends on and supports a specific version of the Python package. We can provide the version we want to update with the == sign and provide the version information.
Downgrade Python Package To The Specific version with Pip
The downgrade is the operation of installing an older version of the specified package. We can downgrade the Python package to the specific version by using the == with the install command.