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

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


当前回答

拉玛纳回答的一个线性版本。

python -c 'import pip, subprocess; [subprocess.call("pip install -U " + d.project_name, shell=1) for d in pip.get_installed_distributions()]'

其他回答

import os
import pip
from subprocess import call, check_call

pip_check_list = ['pip', 'pip3']
pip_list = []
FNULL = open(os.devnull, 'w')


for s_pip in pip_check_list:
    try:
        check_call([s_pip, '-h'], stdout=FNULL)
        pip_list.append(s_pip)
    except FileNotFoundError:
        pass


for dist in pip.get_installed_distributions():
    for pip in pip_list:
        call("{0} install --upgrade ".format(pip) + dist.project_name, shell=True)

我接受了拉玛纳的回答,并使其变得友好。

使用AWK更新包:

pip install -U $(pip freeze | awk -F'[=]' '{print $1}')

Windows PowerShell更新

foreach($p in $(pip freeze)){ pip install -U $p.Split("=")[0]}

你可以试试这个:

for i in ` pip list | awk -F ' ' '{print $1}'`; do pip install --upgrade $i; done

我喜欢使用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包维护之外,非常简单地用于升级。

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