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

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


当前回答

我最近一直在用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 ...

其他回答

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

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)。

通过拉取请求发送给pip人员;同时使用我写的这个pip库解决方案:

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

在我看来,这个选项更简单易懂:

pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`

解释是,pip-list——过时输出所有过时包的列表,格式如下:

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

在awk命令中,NR>2跳过前两条记录(行),{print$1}选择每行的第一个单词(正如SergioAraujo所建议的,我删除了tail-n+3,因为awk确实可以处理跳过记录)。

python -c 'import pip; [pip.main(["install", "--upgrade", d.project_name]) for d in pip.get_installed_distributions()]'

一行!

Windows PowerShell解决方案

pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}