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

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


当前回答

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)

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

其他回答

我在pip问题讨论中找到的最简单、最快的解决方案是:

pip install pipdate
pipdate

资料来源:https://github.com/pypa/pip/issues/3819

您可以使用以下Python代码。与pip冻结不同,这不会打印警告和FIXME错误。对于管道<10.0.1

import pip
from subprocess import call

packages = [dist.project_name for dist in pip.get_installed_distributions()]
call("pip install --upgrade " + ' '.join(packages), shell=True)

对于pip>=10.0.1

import pkg_resources
from subprocess import call

packages = [dist.project_name for dist in pkg_resources.working_set]
call("pip install --upgrade " + ' '.join(packages), 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)。

如果你在macOS上,

确保已安装Homebrew安装jq以读取您将要生成的JSON

brew install jq

更新pip3列表生成的过时包列表中的每个项目--过时

pip3 install --upgrade  `pip3 list --outdated --format json | jq '.[] | .name' | awk -F'"' '{print $2}'`

cmd中的一行:

for /F "delims= " %i in ('pip list --outdated --format=legacy') do pip install -U %i

因此

管道检查

之后应该确保没有中断依赖关系。