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

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


当前回答

要在默认python版本中升级所有pip默认包,只需在终端或命令提示符中运行底部python代码:

import subprocess
import re


pkg_list = subprocess.getoutput('pip freeze')

pkg_list = pkg_list.split('\n')


new_pkg = []
for i in pkg_list:
    re.findall(r"^(.*)==.*", str(i))
    new = re.findall(r"^(.*)==.*", str(i))[0]
    new_pkg.append(new)

for i in new_pkg:
    print(subprocess.getoutput('pip install '+str(i)+' --upgrade'))

其他回答

这里有一个脚本,它只更新过时的包。

import os, sys
from subprocess import check_output, call

file = check_output(["pip.exe",  "list", "--outdated", "--format=legacy"])
line = str(file).split()

for distro in line[::6]:
    call("pip install --upgrade " + distro, shell=True)

对于不输出为传统格式的新版本pip(版本18+):

import os, sys
from subprocess import check_output, call

file = check_output(["pip.exe", "list", "-o", "--format=json"])
line = str(file).split()

for distro in line[1::8]:
    distro = str(distro).strip('"\",')
    call("pip install --upgrade " + distro, shell=True)

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

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

以下一行可能会有所帮助:

(点数>20.00)

pip list--格式冻结--过时|sed的/=.*//g'| xargs-n1 pip install-U

旧版本:pip list--格式冻结--过时|sed的/(.*//g'| xargs-n1 pip install-U

如果发生错误,xargs-n1将继续运行。

如果您需要对省略的内容和引发错误的内容进行更多的“细粒度”控制,则不应添加-n1标志并明确定义要忽略的错误,方法是为每个单独的错误“管道化”以下行:

|sed的/^<错误的第一个字符>.*//'

下面是一个工作示例:

pip list --format freeze --outdated | sed 's/=.*//g' | sed 's/^<First characters of the first error>.*//' | sed 's/^<First characters of the second error>.*//' | xargs pip install -U

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

在蝙蝠脚本中

call pip freeze > requirements.txt
call powershell "(Get-Content requirements.txt) | ForEach-Object { $_ -replace '==', '>=' } | Set-Content requirements.txt"
call pip install -r requirements.txt --upgrade