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, unlike the ActiveState Platform. To ensure your environment doesn’t break on upgrade, you can sign up for a free ActiveState Platform account and import your current requirements.txt, ready to be upgraded.
Python Package Upgrade Checklist
In general, you can use the following steps to perform a package upgrade:
1. 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 <Installation Requirements>
2. Get a list of all the outdated packages
To generate a list of all outdated packages:
pip list --outdated
3. Upgrade outdated packages
Depending on your operating system or virtual environment, refer to the following sections.
Update all Python Packages on Windows
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:
pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}
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:
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
To upgrade all packages using pip with awk on Ubuntu Linux:
pip3 list -o | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print}' | cut -d' ' -f1 | xargs -n1 pip3 install -U
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):
pip freeze > requirements.txt
- Edit requirements.txt, and replace all ‘==’ with ‘>=’. Use the ‘Replace All’ command in the editor.
- Upgrade all outdated packages:
pip install -r requirements.txt --upgrade
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:
import pkg_resources from subprocess import callfor dist in pkg_resources.working_set: call("python -m pip install --upgrade " + dist.<projectname>, shell=True)
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:
- Activate the Pipenv shell that contains the packages to be upgraded:
pipenv shell
- Upgrade all packages:
pipenv update
Modern way to manage Python packages – ActiveState Platform
The ActiveState Platform is a cloud-based build automation and dependency management tool for Python. It provides dependency resolution for:
- Python language cores, including Python 2.7 and Python 3.5+
- Python packages and their dependencies, including:
- Transitive dependencies (ie., dependencies of dependencies)
- Linked C and Fortran libraries, so you can build data science packages
- Operating system-level dependencies for Windows, Linux, and macOS
- Shared dependencies (ie., OpenSSL)
The ActiveState Platform is the only Python package management solution that not only resolves dependencies but also provides workarounds for dependency conflicts.
Simply following the instruction prompts will resolve the conflict, eliminating dependency hell.
You can try the ActiveState Platform for free by creating an account using your email or your GitHub credentials. Start by creating a new Python project, pick the latest version that applies to your project, your OS and start to add packages. Or start by simply importing your requirements.txt file and creating a Python version with all the packages you need. The Platform will automatically pick the right package versions for your environment to ensure security and reproducibility.
Watch this tutorial to learn how to use the ActiveState Platform to create a Python 3.9 environment, and then use the Platform’s Command-Line Interface (State Tool) to install and manage it.
Ready to see for yourself? You can try the ActiveState Platform by signing up for a free account using your email or GitHub credentials.
Just run the following command to install Python 3.9 and our package manager, the State Tool:
Windows
powershell -Command "& $([scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://platform.www.activestate.com/dl/cli/install.ps1'))) -activate-default ActiveState-Labs/Python-3.9Beta"
Linux
sh <(curl -q https://platform.www.activestate.com/dl/cli/install.sh) --activate-default ActiveState-Labs/Python-3.9Beta
Now you can run state install <packagename>. Learn more about how to use the State Tool to manage your Python environment. Or sign up for a free demo and let us show you how it can help improve your dev team’s workflow by compiling Python packages and resolve dependencies in minutes.
Related Links
- How to Download Python Packages
- How To Install Python Packages Using A Script
- How To List Installed Python Packages
- Understanding Python Packages
- Learn More About ActivePython
Frequently Asked Questions
You can pip update all Python packages system-wide to the latest version available in the Python Package Index (PyPI) by running the following command:pip install -r requirements.txt --upgrade
NOTE: The above command assumes all dependencies listed in requirements.txt are upgradeable (ie. are set to >= some version rather than == some version).
Understanding Python packages, modules and libraries.
How do I pip update individual packages in Python?
To update individual packages in Python, run the following command:pip install <packagename> --upgrade
Where packagename is the name of the package to be upgraded.
Learn more about how to install Python packages on Windows.
How do I pip install all Python packages at once?
To install all Python packages at once for your project, first create a requirements.txt file that contains all the packages you need, then run the following command:pip install -r requirements.txt
Learn more about requirements.txt and dependencies.
Can I use pip to update Python?
No, you cannot upgrade Python versions with pip. Pip can only be used to update packages, not Python.
If you want to upgrade Python, download a recent version like the ActivePython installer for Windows, Mac or Linux.
Python Package Upgrade Checklist
Get a list of all the outdated packages
Open a command shell by typing ‘powershell’ in the Search Box of the Task bar
Update All Python Packages On Windows
$ pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}
Update All Python Packages On Linux
$ pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
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):
$ pip freeze > requirements.txt
-
Edit requirements.txt, and replace all ‘==’ with ‘>=’. Use the ‘Replace All’ command in the editor.
-
Upgrade all outdated packages:
$ pip install -r requirements.txt --upgrade
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:
Activate the Pipenv shell that contains the packages to be upgraded
Upgrade all packages
If a requirements.txt file is not available, you can use the pip show command to output all the requirements of a specified package:
Automatically create requirements.txt
You can use the following code to generate a requirements.txt file:
$ pip install pipreqs $ pipreqs /path/to/project
More info related to pipreqs can be found here.
Sometimes you come across pip freeze, but this saves all packages in the environment including those that you don’t use in your current project.
In this article, we will learn to upgrade all Python packages using pip manager. We will use some built-in functions, pip Python manager available in Python to upgrade all packages available in Python. Let’s first have a quick look over what is a pip in Python.
The Pip Python Package Manager
Programmers generally use virtual environments and pip package while working with the Python programming language. When working with projects in Python, users have packages versions being used are defined, which starts growing with time and some packages start to be outdated. pip
Python manager is designed to upgrade the python packages system-wide. Let us look at different ways to use pip to upgrade packages from older versions to newer or latest versions.
Update all packages using pip on Windows
This is the easier way to upgrade packages by using pip
in conjunction with Windows PowerShell. Open your command shell and enter the below command. This will upgrade all packages system-wide to the latest or newer version available in the Python Package Index (PyPI)
.
pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}
Update all packages using pip on Linux
Linux provides a number of ways to use pip
in order to upgrade python packages. This includes two ways using grep and awk.
- Use
grep
to upgrade packages — The grep is to skip editable («-e») package definitions, and the -n1 flag for xargs that prevents stopping everything, if updating one package fails.
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
- Use
awk
to upgrade packages — The below command first lists all outdated packages, then fetches the first column and converts the multiline result fromcut
into a single-line, and forms a space-separated list. It then skips header lines, fetches the first column and takes 1 argument from the pipe left of it, and at last passes it to the command to upgrade the list of packages.
pip3 list -o | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print)' | cut -d' ' -f1 | xargs -n1 pip3 install -U
Command for either Windows or Linux for updating packages
pip freeze
first outputs a list of installed packages into a requirements file (requirements.txt). Then the user needs to edit requirements.txt, and replace all ‘==
’ with ‘>=
’. Use the ‘Replace All’ command in the editor. It then upgrades all outdated packages.
#outputs the list of installed packages
pip freeze > requirements.txt
#updates all packages
pip install -r requirements.txt --upgrade
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 uses pip. Unlike pip freeze
, this command will not print warnings and FIXME errors.
For pip < 10.0.1
import pkg_resources
from subprocess import call
for dist in pkg_resources.working_set:
call("python -m pip install --upgrade " + dist.<projectname>, shell=True)
For pip >= 10.0.1
import pkg_resources
from subprocess import call
packages = [dist.project_name for dist in pkg_resources.working_set]
call("pip install --upgrade " + ' '.join(packages), shell=True)
Updating all Local Packages using pip-review
This command updates only local Python packages. However, this command may not be feasible because it might sometimes generate errors and pip.review
may or may not support Python 3 version. pip-review
is a fork of pip-tools
. pip-review
package works but pip-tools
package no longer works in the latest versions of Python.
$ pip install pip-review
$ pip-review --local --interactive
Conclusion
In this article, we learned different commands to upgrade or update all Python packages using pip manager in Python. We saw two main methods such as pip freeze
and pip review
to update packages.
Пройдите тест, узнайте какой профессии подходите
В работе с Python часто возникает необходимость обновления установленных пакетов. Это может быть связано с тем, что разработчики выпустили новую версию,
Освойте Python на курсе от Skypro. Вас ждут 400 часов обучения и практики (достаточно десяти часов в неделю), подготовка проектов для портфолио, индивидуальная проверка домашних заданий и помощь опытных наставников. Получится, даже если у вас нет опыта в IT.
В работе с Python часто возникает необходимость обновления установленных пакетов. Это может быть связано с тем, что разработчики выпустили новую версию, в которой исправлены ошибки, добавлены новые функции или улучшена производительность.
Рассмотрим пример. Предположим, у вас на компьютере установлены следующие пакеты Python: numpy, pandas и matplotlib. Версии этих пакетов 1.0, 1.0 и 2.0 соответственно. Вы узнали, что вышли новые версии этих пакетов и хотите обновить их все сразу.
Инструмент pip для Python позволяет обновлять пакеты, но изначально не предусматривает возможности обновления всех пакетов сразу. Однако, есть способ обновить все пакеты за один раз.
Для начала, вам нужно получить список всех установленных пакетов. Это можно сделать с помощью команды:
pip freeze > requirements.txt
Эта команда создаст файл requirements.txt, в котором будут перечислены все установленные пакеты и их версии.
Далее, чтобы обновить все пакеты, можно использовать следующую команду:
pip install --upgrade -r requirements.txt
Таким образом, все пакеты из файла requirements.txt будут обновлены до последних версий.
Однако стоит учесть, что этот способ может не подойти для всех ситуаций. В некоторых случаях, обновление одного пакета может вызвать проблемы с другими пакетами, которые зависят от этого пакета. Поэтому всегда стоит подходить к обновлению пакетов с осторожностью.
Важно помнить, что pip не предоставляет встроенной функции для обновления всех пакетов сразу. Поэтому, если вам нужно обновить все пакеты, вам придется использовать немного другой подход, как было показано выше.
Изучайте Python на онлайн-курсе от Skypro «Python-разработчик». Программа рассчитана на новичков без опыта программирования и технического образования. Курс проходит в формате записанных коротких видеолекций. Будет много проверочных заданий и мастер-классов. В конце каждой недели — живая встреча с экспертами в разработке для ответов на вопросы и разбора домашек.
Python is popular for its built-in bundled-up simplicity to achieve the most common tasks. Also, it offers a plethora of external packages (collection of modules and libraries) that can be imported and installed pertaining to particular use cases and the complexity of the solution. As this popular saying goes, “with power comes great responsibility”, use of more and more packages may lead to undesired dependency issues like dependency hell. Therefore, as we covered in our previous article, Managing Python Dependencies with Virtual Environments becomes inevitable.
For this particular reason, the Python pip — used to install Python packages — does not have a built-in command to update all packages in one go. Instead, in an attempt to efficiently manage upgrades and avoid dependency conflicts, independent virtual environments should be used for each project.
In this article, we will discuss how to update all Python packages for a project and best practices to keep in mind when doing so.
Table of Contents
- Pinned and Unpinned Packages
- The Package Update Checklist
- Update Python Packages on Windows
- Update Python Packages on Linux
- OS-Independent Upgrade of Python Packages
- Update Python Packages in Virtual Environment
- Update Python Packages in Pipenv Virtual Environment
- Conclusion
Pinned and Unpinned Packages
Amongst the best practices to manage packages in Python is to pin all packages along with their version to the specific environment. This ensures that the environment is consistent and functional when reproduced later.
- Pinned packages are denoted by the “==” syntax in the requirements.txt file, such as requests==2.20.0. Such packages generally offer the core functionality of the solution and should only be updated in case of critical security bugs and vulnerability requirements.
- Unpinned packages are denoted by the “>=” syntax in the requirements.txt file. Such packages are okay to be updated to the latest versions for efficiency and performance improvements, in addition to new functionality
Most popular packages offer frequent updates to patch bugs and vulnerabilities. It is advised, concerning the security of a solution, to keep all packages up-to-date. The decision to update pinned packages lies solely with the development team as to what the newer version of the package entails. Security updates should surely be incorporated, whilst newer functionality may be ignored depending on the use case.
Pip is the de facto package management solution for installing updates system-wide whilst for virtual environments, the dedicated package manager of the virtual environment library should be used. As our team recommends the use of Pipenv for dependency management using virtual environments, the pipenv package manager is a suitable solution for updating all Python packages.
The Package Update Checklist
The following steps offer a general approach to updating all Python packages, irrespective of environment and operating system:
- Ensure Python and Pip are installed using the following commands:
python --version
pip --version
- Update Pip and Wheel to the latest version using:
pip install --upgrade pip wheel
- Fetch the list of outdated packages using:
pip list --outdated
- Update outdated packages.
We will now explore how to achieve the last step in different environments and operating systems.
Update Python Packages on Windows
Updating all Python packages on the Windows operating system is fairly straightforward.
Just follow these steps:
- Open up the Windows PowerShell by typing “powershell” in the search box of Taskbar or using the command prompt.
- Use Pip in conjunction with the Windows PowerShell to execute the following command:
pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}
Please note that this technique will update all the Python packages system-wide. The latest version will be mapped using the Python Package Index (PyPI).
Update Python Packages on Linux
Linux offers numerous approaches to updating all Python packages in one go. The two popular methods are to use Pip in conjunction with grep or awk:
- To use pip and grep, execute the following command:
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
- To use pip and awk, execute the following command:
pip3 list -o | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print)' | cut -d' ' -f1 | xargs -n1 pip3 install -U
As is the case with Windows, this technique would update all Python packages system-wide using the Python Package Index (PyPI).
OS-Independent Upgrade of Python Packages
If you work with multiple operating systems seamlessly and efficiently and wish to explore an OS-independent technique, you may use the following workaround:
- Write a list of all installed packages into a requirements.txt file using:
pip freeze > requirements.txt
- Edit the requirements.txt file and unpin all packages by replacing “==” with “>=”. “Find and Replace All” functionality of common text editors like VS Code and Notepad might be useful here.
- Update all outdated packages using the following command:
pip install -r requirements.txt --upgrade
If you are working with the root Python installation, this technique would update the packages system-wide. If the requirements.txt file is linked to a particular virtual environment, only the packages in the virtual environment will be impacted.
Update Python Packages in Virtual Environment
You might have guessed by now that updating all Python packages in a virtual environment is as simple as updating the requirements.txt file, as discussed in the previous section.
Another approach is to use the following Python script to update all the unpinned packages:
import pkg_resources from subprocess import call for dist in pkg_resources.working_set: call("python -m pip install --upgrade " + dist.<projectname>, shell=True)
Update Python Packages in Pipenv Virtual Environment
As we actively vouch for the use of Pipenv for dependency management in Python, it would be unjust to not share the approach of updating all Python packages in a Pipenv virtual environment.
To update all unpinned packages in a specific Pipenv environment, follow these steps:
- Activate the pipenv shell containing the packages, using:
pipenv shell
- Update all packages using:
pipenv update
Conclusion
In this article, we explored numerous approaches to updating all Python packages for a project in a seamless and efficient way. We explored best practices of setting up pinned and unpinned packages for agility, and techniques to update the packages in individual and multiple environments, depending on the operating system and use of virtual environments.
We hope this was an insightful read to achieve the simple task of updating packages without writing another long script off the internet or installing an external package to update them. Happy Coding!