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

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


当前回答

我试过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)

其他回答

具有管理员权限的PowerShell 5.1、Python 3.6.5和pip版本10.0.1中的一行:

pip list -o --format json | ConvertFrom-Json | foreach {pip install $_.name -U --no-warn-script-location}

如果列表中没有破损的包裹或特殊的轮子,它会顺利工作。。。

下面是用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更新所有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)

这应该更有效:

pip3 list -o | grep -v -i warning | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print}' | cut -d' ' -f1 | xargs -n1 pip3 install -U

pip-list-o列出过时的包;grep-v-i warning反向匹配警告以避免更新时出错cut-f1-d1''返回第一个单词-过时包的名称;tr“\n|\r”“”将剪切的多行结果转换为单行、空格分隔的列表;awk“{if(NR>=3)print}”跳过标题行cut-d“”-f1获取第一列xargs-n1 pip install-U从管道左侧获取1个参数,并将其传递给命令以升级包列表。

这似乎更简洁。

pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U

说明:

pip-list——过时的代码行如下

urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]

在cut-d“”-f1中,-d“”将“空格”设置为分隔符,-f1表示获取第一列。

因此,上述行变为:

urllib3
wheel

然后将它们传递给xargs以运行命令pipinstall-U,每一行都作为附加参数

-n1将传递给每个命令pip install-U的参数数限制为1