是否可以使用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)。

其他回答

以下是通过pip更新所有Python 3包(在激活的virtualenv中)的代码:

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)

我试过Ramana的代码,我发现在Ubuntu上,每个命令都必须写sudo。这是我在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)

相当惊人的蛋黄使这很容易。

pip install yolk3k # Don't install `yolk`, see https://github.com/cakebread/yolk/issues/35
yolk --upgrade

有关蛋黄的更多信息:https://pypi.python.org/pypi/yolk/0.4.3

它可以做很多你可能会发现有用的事情。

pip install --upgrade `pip list --format=freeze | cut -d '=' -f 1`

pip-list--format=freeze包括pip和setuptools。pip冻结不会。

通过拉取请求发送给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