是否可以使用pip一次性升级所有Python包?

注意:官方问题跟踪器上对此有一个功能请求。


当前回答

这里有一个脚本,它只更新过时的包。

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)

对于不输出为传统格式的新版本pip(版本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)

其他回答

下面是用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])

我喜欢使用pip工具来处理这个过程。

打包pip工具提供两个脚本:

pipcompile:用于从requirement.in文件创建可行的requirements.txt。pip-sync:用于同步本地环境pip存储库以匹配requirements.txt文件。

如果我想升级特定软件包,请说:

django==3.2.12

to

django==3.2.16

然后,我可以在requirements.in中更改django的基本版本,运行pipcompile,然后运行pipsync。这将通过删除旧版本,然后安装新版本,有效地升级django(以及所有依赖的软件包)。

除了pip包维护之外,非常简单地用于升级。

在蝙蝠脚本中

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

在查阅Rob van der Woude的for优秀文档后,Windows版本:

for /F "delims===" %i in ('pip freeze') do pip install --upgrade %i

使用pipupgrade。。。最新版本2019

$ pip install pipupgrade
$ pipupgrade --verbose --latest --yes

pipupgrade帮助您从requirements.txt文件升级系统、本地或软件包!它还选择性地升级不破坏更改的包。

pipupgrade还确保升级多个Python环境中的包。它与Python2.7+、Python23.4+和pip9+、pip10+、pip18+、pip19+兼容。

注:我是该工具的作者。