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

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


当前回答

拉玛纳的回答对我来说是最好的,但我不得不补充几点:

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

站点包检查排除了我的开发包,因为它们不在系统站点包目录中。try-except只是跳过已从PyPI中删除的包。

对于endolith:我也希望有一个简单的pip.install(dist.key,upgrade=True),但它看起来不像是要让命令行以外的任何东西使用pip(文档没有提到内部API,pip开发人员也没有使用docstring)。

其他回答

这是Python 3的PowerShell解决方案:

pip3 list --outdated --format=legacy | ForEach { pip3 install -U $_.split(" ")[0] }

对于Python 2:

pip2 list --outdated --format=legacy | ForEach { pip2 install -U $_.split(" ")[0] }

这将逐个升级软件包。因此

pip3 check
pip2 check

之后应该确保没有中断依赖关系。

我最近一直在用pur。这很简单,切中要害。它会更新您的requirements.txt文件以反映升级,然后您可以像往常一样使用requirements.txt文件进行升级。

$ 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 ...

如果您安装了pip<22.3,则使用纯Bash/Z外壳一个衬垫实现:

for p in $(pip list -o --format freeze); do pip install -U ${p%%=*}; done

或者,以一种格式良好的方式:

for p in $(pip list -o --format freeze)
do
    pip install -U ${p%%=*}
done

在这之后,您将得到pip>=22.3,其中-o和--format冻结是互斥的,您不能再使用这一行。

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

for /F "delims===" %i in ('pip freeze') do pip install --upgrade %i
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U