Asked
Viewed
1.8m times
Is it possible to upgrade all Python packages at one time with pip
?
Note: that there is a feature request for this on the official issue tracker.
asked Apr 27, 2010 at 9:23
thedjpetersenthedjpetersen
28k4 gold badges26 silver badges28 bronze badges
4
There isn’t a built-in flag yet. Starting with pip version 22.3, the --outdated
and --format=freeze
have become mutually exclusive. Use Python, to parse the JSON output:
pip --disable-pip-version-check list --outdated --format=json | python -c "import json, sys; print('\n'.join([x['name'] for x in json.load(sys.stdin)]))" | xargs -n1 pip install -U
If you are using pip<22.3
you can use:
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
For older versions of pip
:
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
-
The
grep
is to skip editable («-e») package definitions, as suggested by @jawache. (Yes, you could replacegrep
+cut
withsed
orawk
orperl
or…). -
The
-n1
flag forxargs
prevents stopping everything if updating one package fails (thanks @andsens).
Note: there are infinite potential variations for this. I’m trying to keep this answer short and simple, but please do suggest variations in the comments!
answered Aug 10, 2010 at 19:56
64
To upgrade all local packages, you can install pip-review
:
$ pip install pip-review
After that, you can either upgrade the packages interactively:
$ pip-review --local --interactive
Or automatically:
$ pip-review --local --auto
pip-review
is a fork of pip-tools
. See pip-tools
issue mentioned by @knedlsepp. pip-review
package works but pip-tools
package no longer works. pip-review
is looking for a new maintainer.
pip-review
works on Windows since version 0.5.
answered Apr 29, 2013 at 0:34
jfsjfs
401k196 gold badges998 silver badges1677 bronze badges
21
You can use the following Python code. Unlike pip freeze
, this will not print warnings and FIXME errors.
For pip < 10.0.1
import pip
from subprocess import call
packages = [dist.project_name for dist in pip.get_installed_distributions()]
call("pip install --upgrade " + ' '.join(packages), 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)
MSS
3,3311 gold badge20 silver badges50 bronze badges
answered Apr 30, 2011 at 3:31
26
The following works on Windows and should be good for others too ($
is whatever directory you’re in, in the command prompt. For example, C:/Users/Username).
Do
$ pip freeze > requirements.txt
Open the text file, replace the ==
with >=
, or have sed do it for you:
$ sed -i 's/==/>=/g' requirements.txt
and execute:
$ pip install -r requirements.txt --upgrade
If you have a problem with a certain package stalling the upgrade (NumPy sometimes), just go to the directory ($), comment out the name (add a #
before it) and run the upgrade again. You can later uncomment that section back. This is also great for copying Python global environments.
Another way:
I also like the pip-review method:
py2
$ pip install pip-review
$ pip-review --local --interactive
py3
$ pip3 install pip-review
$ py -3 -m pip-review --local --interactive
You can select ‘a’ to upgrade all packages; if one upgrade fails, run it again and it continues at the next one.
answered Nov 12, 2015 at 9:20
azazelspeaksazazelspeaks
5,7752 gold badges22 silver badges39 bronze badges
12
Use pipupgrade! … last release 2019
pip install pipupgrade
pipupgrade --verbose --latest --yes
pipupgrade helps you upgrade your system, local or packages from a requirements.txt
file! It also selectively upgrades packages that don’t break change.
pipupgrade also ensures to upgrade packages present within multiple Python environments. It is compatible with Python 2.7+, Python 3.4+ and pip 9+, pip 10+, pip 18+, pip 19+.
Note: I’m the author of the tool.
answered Jan 16, 2019 at 1:26
25
Windows version after consulting the excellent documentation for FOR
by Rob van der Woude:
for /F "delims===" %i in ('pip freeze') do pip install --upgrade %i
answered Feb 25, 2012 at 18:04
Piotr DobrogostPiotr Dobrogost
41.4k40 gold badges236 silver badges366 bronze badges
8
This option seems to me more straightforward and readable:
pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`
The explanation is that pip list --outdated
outputs a list of all the outdated packages in this format:
Package Version Latest Type
--------- ------- ------ -----
fonttools 3.31.0 3.32.0 wheel
urllib3 1.24 1.24.1 wheel
requests 2.20.0 2.20.1 wheel
In the AWK command, NR>2
skips the first two records (lines) and {print $1}
selects the first word of each line (as suggested by SergioAraujo, I removed tail -n +3
since awk
can indeed handle skipping records).
answered Nov 21, 2014 at 23:15
MarcMarc
1,6301 gold badge15 silver badges17 bronze badges
2
The following one-liner might prove of help:
(pip >= 22.3)
as per this readable answer:
pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`
or as per the accepted answer:
pip --disable-pip-version-check list --outdated --format=json |
python -c "import json, sys; print('\n'.join([x['name'] for x in json.load(sys.stdin)]))" |
xargs -n1 pip install -U
(pip 20.0 < 22.3)
pip list --format freeze --outdated | sed 's/=.*//g' | xargs -n1 pip install -U
Older Versions:
pip list --format freeze --outdated | sed 's/(.*//g' | xargs -n1 pip install -U
xargs -n1
keeps going if an error occurs.
If you need more «fine grained» control over what is omitted and what raises an error you should not add the -n1
flag and explicitly define the errors to ignore, by «piping» the following line for each separate error:
| sed 's/^<First characters of the error>.*//'
Here is a working example:
pip list --format freeze --outdated | sed 's/=.*//g' | sed 's/^<First characters of the first error>.*//' | sed 's/^<First characters of the second error>.*//' | xargs pip install -U
answered Mar 7, 2014 at 20:25
raratiruraratiru
8,8584 gold badges73 silver badges113 bronze badges
3
You can just print the packages that are outdated:
pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:'
answered Jun 10, 2011 at 12:50
janritojanrito
8856 silver badges4 bronze badges
3
More Robust Solution
For pip3, use this:
pip3 freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip3 install -U \1/p' |sh
For pip, just remove the 3s as such:
pip freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip install -U \1/p' |sh
OS X Oddity
OS X, as of July 2017, ships with a very old version of sed (a dozen years old). To get extended regular expressions, use -E
instead of -r
in the solution above.
Solving Issues with Popular Solutions
This solution is well designed and tested1, whereas there are problems with even the most popular solutions.
- Portability issues due to changing pip command line features
- Crashing of xargs because of common pip or pip3 child process failures
- Crowded logging from the raw xargs output
- Relying on a Python-to-OS bridge while potentially upgrading it3
The above command uses the simplest and most portable pip syntax in combination with sed and sh to overcome these issues completely. Details of the sed operation can be scrutinized with the commented version2.
Details
[1] Tested and regularly used in a Linux 4.8.16-200.fc24.x86_64 cluster and tested on five other Linux/Unix flavors. It also runs on Cygwin64 installed on Windows 10. Testing on iOS is needed.
[2] To see the anatomy of the command more clearly, this is the exact equivalent of the above pip3 command with comments:
# Match lines from pip's local package list output
# that meet the following three criteria and pass the
# package name to the replacement string in group 1.
# (a) Do not start with invalid characters
# (b) Follow the rule of no white space in the package names
# (c) Immediately follow the package name with an equal sign
sed="s/^([^=# \t\\][^ \t=]*)=.*"
# Separate the output of package upgrades with a blank line
sed="$sed/echo"
# Indicate what package is being processed
sed="$sed; echo Processing \1 ..."
# Perform the upgrade using just the valid package name
sed="$sed; pip3 install -U \1"
# Output the commands
sed="$sed/p"
# Stream edit the list as above
# and pass the commands to a shell
pip3 freeze --local | sed -rn "$sed" | sh
[3] Upgrading a Python or PIP component that is also used in the upgrading of a Python or PIP component can be a potential cause of a deadlock or package database corruption.
Michel
7674 silver badges19 bronze badges
answered Feb 20, 2017 at 0:45
2
I had the same problem with upgrading. Thing is, I never upgrade all packages. I upgrade only what I need, because project may break.
Because there was no easy way for upgrading package by package, and updating the requirements.txt file, I wrote this pip-upgrader which also updates the versions in your requirements.txt
file for the packages chosen (or all packages).
Installation
pip install pip-upgrader
Usage
Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).
cd
into your project directory, then run:
pip-upgrade
Advanced usage
If the requirements are placed in a non-standard location, send them as arguments:
pip-upgrade path/to/requirements.txt
If you already know what package you want to upgrade, simply send them as arguments:
pip-upgrade -p django -p celery -p dateutil
If you need to upgrade to pre-release / post-release version, add --prerelease
argument to your command.
Full disclosure: I wrote this package.
answered Apr 26, 2017 at 18:43
6
This seems more concise.
pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U
Explanation:
pip list --outdated
gets lines like these
urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]
In cut -d ' ' -f1
, -d ' '
sets «space» as the delimiter, -f1
means to get the first column.
So the above lines becomes:
urllib3
wheel
Then pass them to xargs
to run the command, pip install -U
, with each line as appending arguments.
-n1
limits the number of arguments passed to each command pip install -U
to be 1.
answered Jun 10, 2016 at 3:47
Shihao XuShihao Xu
1,1602 gold badges10 silver badges23 bronze badges
3
One-liner version of Ramana’s answer.
python -c 'import pip, subprocess; [subprocess.call("pip install -U " + d.project_name, shell=1) for d in pip.get_installed_distributions()]'
answered May 22, 2013 at 12:42
Samuel KatzSamuel Katz
24.1k8 gold badges71 silver badges57 bronze badges
2
From yolk:
pip install -U `yolk -U | awk '{print $1}' | uniq`
However, you need to get yolk first:
sudo pip install -U yolk
answered Apr 3, 2012 at 21:38
tkrtkr
3583 silver badges3 bronze badges
1
The pip_upgrade_outdated
(based on this older script) does the job. According to its documentation:
usage: pip_upgrade_outdated [-h] [-3 | -2 | --pip_cmd PIP_CMD]
[--serial | --parallel] [--dry_run] [--verbose]
[--version]
Upgrade outdated python packages with pip.
optional arguments:
-h, --help show this help message and exit
-3 use pip3
-2 use pip2
--pip_cmd PIP_CMD use PIP_CMD (default pip)
--serial, -s upgrade in serial (default)
--parallel, -p upgrade in parallel
--dry_run, -n get list, but don't upgrade
--verbose, -v may be specified multiple times
--version show program's version number and exit
Step 1:
pip install pip-upgrade-outdated
Step 2:
pip_upgrade_outdated
answered Apr 13, 2018 at 11:24
adrinadrin
4,5413 gold badges34 silver badges50 bronze badges
4
When using a virtualenv and if you just want to upgrade packages added to your virtualenv, you may want to do:
pip install `pip freeze -l | cut --fields=1 -d = -` --upgrade
answered Sep 13, 2011 at 9:42
brunobordbrunobord
2943 silver badges4 bronze badges
Updating Python packages on 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
Source: How to Update All Python Packages
answered Feb 11, 2021 at 2:24
Isaque Elcio Isaque Elcio
1,0499 silver badges4 bronze badges
3
Windows PowerShell solution
pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}
answered Sep 16, 2016 at 9:07
5
Use AWK update packages:
pip install -U $(pip freeze | awk -F'[=]' '{print $1}')
Windows PowerShell update
foreach($p in $(pip freeze)){ pip install -U $p.Split("=")[0]}
answered Nov 9, 2017 at 9:19
JohnDHHJohnDHH
4093 silver badges7 bronze badges
1
One line in PowerShell 5.1 with administrator rights, Python 3.6.5, and pip version 10.0.1:
pip list -o --format json | ConvertFrom-Json | foreach {pip install $_.name -U --no-warn-script-location}
It works smoothly if there are no broken packages or special wheels in the list…
answered Jun 25, 2018 at 11:56
2
If you have pip<22.3
installed, a pure Bash/Z shell one-liner for achieving that:
for p in $(pip list -o --format freeze); do pip install -U ${p%%=*}; done
Or, in a nicely-formatted way:
for p in $(pip list -o --format freeze)
do
pip install -U ${p%%=*}
done
After this you will have pip>=22.3
in which -o
and --format freeze
are mutually exclusive, and you can no longer use this one-liner.
answered Nov 29, 2018 at 10:31
2
The rather amazing yolk makes this easy.
pip install yolk3k # Don't install `yolk`, see https://github.com/cakebread/yolk/issues/35
yolk --upgrade
For more information on yolk: https://pypi.python.org/pypi/yolk/0.4.3
It can do lots of things you’ll probably find useful.
answered Jun 1, 2016 at 7:39
user1175849user1175849
1,3059 silver badges14 bronze badges
0
You can try this:
for i in `pip list | awk -F ' ' '{print $1}'`; do pip install --upgrade $i; done
answered Jul 17, 2013 at 1:43
3WA羽山秋人3WA羽山秋人
1321 silver badge5 bronze badges
1
The shortest and easiest on Windows.
pip freeze > requirements.txt && pip install --upgrade -r requirements.txt && rm requirements.txt
Pang
9,623146 gold badges81 silver badges122 bronze badges
answered Apr 23, 2018 at 7:06
AnkireddyAnkireddy
1791 silver badge6 bronze badges
2
Use:
pip install -r <(pip freeze) --upgrade
answered Sep 12, 2017 at 16:50
There is not necessary to be so troublesome or install some package.
Update pip packages on Linux shell:
pip list --outdated --format=freeze | awk -F"==" '{print $1}' | xargs -i pip install -U {}
Update pip packages on Windows powershell:
pip list --outdated --format=freeze | ForEach { pip install -U $_.split("==")[0] }
Some points:
- Replace
pip
as your python version topip3
orpip2
. pip list --outdated
to check outdated pip packages.--format
on my pip version 22.0.3 only has 3 types: columns (default), freeze, or json.freeze
is better option in command pipes.- Keep command simple and usable as many systems as possible.
answered Mar 1, 2022 at 6:23
Linus SEOLinus SEO
1212 silver badges6 bronze badges
2
Ramana’s answer worked the best for me, of those here, but I had to add a few catches:
import pip
for dist in pip.get_installed_distributions():
if 'site-packages' in dist.location:
try:
pip.call_subprocess(['pip', 'install', '-U', dist.key])
except Exception, exc:
print exc
The site-packages
check excludes my development packages, because they are not located in the system site-packages directory. The try-except simply skips packages that have been removed from PyPI.
To endolith: I was hoping for an easy pip.install(dist.key, upgrade=True)
, too, but it doesn’t look like pip was meant to be used by anything but the command line (the docs don’t mention the internal API, and the pip developers didn’t use docstrings).
answered Oct 27, 2012 at 22:56
chbrownchbrown
11.9k2 gold badges52 silver badges60 bronze badges
1
This ought to be more effective:
pip3 list -o | grep -v -i warning | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print}' | cut -d' ' -f1 | xargs -n1 pip3 install -U
pip list -o
lists outdated packages;grep -v -i warning
inverted match onwarning
to avoid errors when updatingcut -f1 -d1' '
returns the first word — the name of the outdated package;tr "\n|\r" " "
converts the multiline result fromcut
into a single-line, space-separated list;awk '{if(NR>=3)print}'
skips header linescut -d' ' -f1
fetches the first columnxargs -n1 pip install -U
takes 1 argument from the pipe left of it, and passes it to the command to upgrade the list of packages.
answered Oct 9, 2014 at 14:23
Alex VAlex V
3534 silver badges10 bronze badges
4
Sent through a pull-request to the pip folks; in the meantime use this pip library solution I wrote:
from pip import get_installed_distributions
from pip.commands import install
install_cmd = install.InstallCommand()
options, args = install_cmd.parse_args([package.project_name
for package in
get_installed_distributions()])
options.upgrade = True
install_cmd.run(options, args) # Chuck this in a try/except and print as wanted
answered Jan 26, 2014 at 9:31
Samuel MarksSamuel Marks
1,6411 gold badge20 silver badges27 bronze badges
2
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.activestate.com/dl/cli/install.ps1'))) -activate-default ActiveState-Labs/Python-3.9Beta"
Linux
sh <(curl -q https://platform.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
Frequently Asked Questions
Can I pip update all Python packages?
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.
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.
You can use the pip freeze
command to generate a requirements file that includes all of the current packages and their versions, and then use pip install -r
to upgrade all packages to the latest available versions. Here’s an example of how you can do this:
- Run the following command to generate a requirements file:
pip freeze > requirements.txt
-
Open the requirements file in a text editor and delete the version numbers next to each package. The file should now contain a list of package names, one per line.
-
Save the file and close the text editor.
-
Run the following command to upgrade all packages to the latest available versions:
pip install -r requirements.txt --upgrade
This will upgrade all of the packages listed in the requirements file to the latest available versions.
Alternatively, you can use the pip list -o
command to list outdated packages, and then use pip install --upgrade
to upgrade a specific package. For example:
This will list all outdated packages and their current and latest versions. To upgrade a specific package, you can run the following command:
pip install --upgrade package_name
Replace package_name
with the name of the package you want to upgrade.
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.