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.
Join Stack Overflow to learn, share knowledge, and build your career.
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.
See all outdated packages
pip list --outdated --format=columns
Install
sudo pip install pipdate
then type
sudo -H pipdate
The below Windows cmd
snippet does the following:
- Upgrades
pip
to latest version.- Upgrades all outdated packages.
- For each packages being upgraded checks
requirements.txt
for any version specifiers.
@echo off
Setlocal EnableDelayedExpansion
rem https://stackoverflow.com/questions/2720014/
echo Upgrading pip...
python -m pip install --upgrade pip
echo.
echo Upgrading packages...
set upgrade_count=0
pip list --outdated > pip-upgrade-outdated.txt
for /F "skip=2 tokens=1,3 delims= " %%i in (pip-upgrade-outdated.txt) do (
echo ^>%%i
set package=%%i
set latest=%%j
set requirements=!package!
rem for each outdated package check for any version requirements:
set dotest=1
for /F %%r in (.\python\requirements.txt) do (
if !dotest!==1 (
call :substr "%%r" !package! _substr
rem check if a given line refers to a package we are about to upgrade:
if "%%r" NEQ !_substr! (
rem check if the line contains more than just a package name:
if "%%r" NEQ "!package!" (
rem set requirements to the contents of the line:
echo requirements: %%r, latest: !latest!
set requirements=%%r
)
rem stop testing after the first instance found,
rem prevents from mistakenly matching "py" with "pylint", "numpy" etc.
rem requirements.txt must be structured with shorter names going first
set dotest=0
)
)
)
rem pip install !requirements!
pip install --upgrade !requirements!
set /a "upgrade_count+=1"
echo.
)
if !upgrade_count!==0 (
echo All packages are up to date.
) else (
type pip-upgrade-outdated.txt
)
if "%1" neq "-silent" (
echo.
set /p temp="> Press Enter to exit..."
)
exit /b
:substr
rem string substition done in a separate subroutine -
rem allows expand both variables in the substring syntax.
rem replaces str_search with an empty string.
rem returns the result in the 3rd parameter, passed by reference from the caller.
set str_source=%1
set str_search=%2
set str_result=!str_source:%str_search%=!
set "%~3=!str_result!"
rem echo !str_source!, !str_search!, !str_result!
exit /b
for /F "skip=2" %G in ('pip list --outdated') do pip install %G --upgrade
should do the job as well however preceding python -m pip install --upgrade pip
isn't a bad idea:)
– JosefZ
Mar 20 '20 at 20:17
Here is my variation on rbp's answer, which bypasses "editable" and development distributions. It shares two flaws of the original: it re-downloads and reinstalls unnecessarily; and an error on one package will prevent the upgrade of every package after that.
pip freeze |sed -ne 's/==.*//p' |xargs pip install -U --
Related bug reports, a bit disjointed after the migration from Bitbucket:
Here is a script that only updates the outdated packages.
import os, sys
from subprocess import check_output, call
file = check_output(["pip.exe", "list", "--outdated", "--format=legacy"])
line = str(file).split()
for distro in line[::6]:
call("pip install --upgrade " + distro, shell=True)
For a new version of pip that does not output as a legacy format (version 18+):
import os, sys
from subprocess import check_output, call
file = check_output(["pip.exe", "list", "-o", "--format=json"])
line = str(file).split()
for distro in line[1::8]:
distro = str(distro).strip('"\",')
call("pip install --upgrade " + distro, shell=True)
Use:
import pip
pkgs = [p.key for p in pip.get_installed_distributions()]
for pkg in pkgs:
pip.main(['install', '--upgrade', pkg])
Or even:
import pip
commands = ['install', '--upgrade']
pkgs = commands.extend([p.key for p in pip.get_installed_distributions()])
pip.main(commands)
It works fast as it is not constantly launching a shell.
Here's the code for updating all Python 3 packages (in the activated virtualenv
) via pip:
import pkg_resources
from subprocess import call
for dist in pkg_resources.working_set:
call("python3 -m pip install --upgrade " + dist.project_name, shell=True)
I've been using pur lately. It's simple and to the point. It updates your requirements.txt
file to reflect the upgrades and you can then upgrade with your requirements.txt
file as usual.
$ pip install pur
...
Successfully installed pur-4.0.1
$ pur
Updated boto3: 1.4.2 -> 1.4.4
Updated Django: 1.10.4 -> 1.10.5
Updated django-bootstrap3: 7.1.0 -> 8.1.0
All requirements up-to-date.
$ pip install --upgrade -r requirements.txt
Successfully installed Django-1.10.5 ...
I have tried the code of Ramana and I found out on Ubuntu you have to write sudo
for each command. Here is my script which works fine on Ubuntu 13.10 (Saucy Salamander):
#!/usr/bin/env python
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("sudo pip install --upgrade " + dist.project_name, shell=True)
Here is another way of doing with a script in Python:
import pip, tempfile, contextlib
with tempfile.TemporaryFile('w+') as temp:
with contextlib.redirect_stdout(temp):
pip.main(['list', '-o'])
temp.seek(0)
for line in temp:
pk = line.split()[0]
print('--> updating', pk, '<--')
pip.main(['install', '-U', pk])
A JSON + jq answer:
pip list -o --format json | jq '.[] | .name' | xargs pip install -U
import os
import pip
from subprocess import call, check_call
pip_check_list = ['pip', 'pip3']
pip_list = []
FNULL = open(os.devnull, 'w')
for s_pip in pip_check_list:
try:
check_call([s_pip, '-h'], stdout=FNULL)
pip_list.append(s_pip)
except FileNotFoundError:
pass
for dist in pip.get_installed_distributions():
for pip in pip_list:
call("{0} install --upgrade ".format(pip) + dist.project_name, shell=True)
I took Ramana's answer and made it pip3 friendly.
Updating Python Packages On Windows Or Linux
1-Output a list of installed packages into a requirements file (requirements.txt):
pip freeze > requirements.txt
2- Edit requirements.txt, and replace all ‘==’ with ‘>=’. Use the ‘Replace All’ command in the editor.
3 - Upgrade all outdated packages
pip install -r requirements.txt --upgrade
Source:https://www.activestate.com/resources/quick-reads/how-to-update-all-python-packages/
One line in cmd:
for /F "delims= " %i in ('pip list --outdated --format=legacy') do pip install -U %i
So a
pip check
afterwards should make sure no dependencies are broken.
As another answer here stated:
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
Is a possible solution: Some comments here, myself included, had issues with permissions while using this command. A little change to the following solved those for me.
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 sudo -H pip install -U
Note the added sudo -H
which allowed the command to run with root permissions.
sudo -H
) version when updating the packages for your whole system.
– Manu CJ
Nov 20 '17 at 16:47
The shortest and easiest I can find:
pip install -U $(pip freeze | cut -d"=" -f1)
The $(cmd)
key allows you to wrap any shell command line (it returns its output).
If you are on macOS,
brew install jq
pip3 list --outdated
pip3 install --upgrade `pip3 list --outdated --format json | jq '.[] | .name' | awk -F'"' '{print $2}'`
python -c 'import pip; [pip.main(["install", "--upgrade", d.project_name]) for d in pip.get_installed_distributions()]'
One liner!
If you want upgrade only packaged installed by pip, and to avoid upgrading packages that are installed by other tools (like apt, yum etc.), then you can use this script that I use on my Ubuntu (maybe works also on other distros) - based on this post:
printf "To update with pip: pip install -U"
pip list --outdated 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo
for in a bat script
call pip freeze > requirements.txt
call powershell "(Get-Content requirements.txt) | ForEach-Object { $_ -replace '==', '>=' } | Set-Content requirements.txt"
call pip install -r requirements.txt --upgrade
to upgrade all of your pip default packages in your default python version just run the bottom python code in your terminal or command prompt:
import subprocess
import re
pkg_list = subprocess.getoutput('pip freeze')
pkg_list = pkg_list.split('\n')
new_pkg = []
for i in pkg_list:
re.findall(r"^(.*)==.*", str(i))
new = re.findall(r"^(.*)==.*", str(i))[0]
new_pkg.append(new)
for i in new_pkg:
print(subprocess.getoutput('pip install '+str(i)+' --upgrade'))
pip freeze
(likebundle install
ornpm shrinkwrap
). Best to save a copy of that before tinkering. – Colonel Panic May 22 '13 at 13:01