是否可以使用pip一次性升级所有Python包?
注意:官方问题跟踪器上对此有一个功能请求。
是否可以使用pip一次性升级所有Python包?
注意:官方问题跟踪器上对此有一个功能请求。
当前回答
这里有一个脚本,它只更新过时的包。
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)
其他回答
我在升级方面也遇到了同样的问题。问题是,我从不升级所有包。我只升级我需要的,因为项目可能会中断。
因为没有一种简单的方法来逐个包升级和更新requirements.txt文件,所以我编写了这个pip升级程序,它还更新了所选包(或所有包)的requirements.txt文件中的版本。
安装
pip install pip-upgrader
用法
激活virtualenv(这很重要,因为它还将在当前virtualenv中安装升级包的新版本)。
cd到项目目录中,然后运行:
pip-upgrade
高级用法
如果需求放置在非标准位置,请将其作为参数发送:
pip-upgrade path/to/requirements.txt
如果您已经知道要升级的软件包,只需将其作为参数发送:
pip-upgrade -p django -p celery -p dateutil
如果需要升级到发布前/发布后版本,请在命令中添加--prerelease参数。
完全披露:我写了这个包裹。
还没有内置标志。从pip版本22.3开始,--过时和--format=freeze变得互斥。使用Python解析json输出:
pip --disable-pip-version-check list --outdated --format=json | python -c "import json, sys; print('\n'.join([x['name'] for x in json.load(sys.stdin)]))"
如果您正在使用pip<22.3,则可以使用:
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
对于旧版本的pip:
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
grep是跳过可编辑(“-e”)包定义,正如@jawache所建议的那样。(是的,您可以用sed、awk、perl或…替换grep+cut)。xargs的-n1标志防止在更新一个包失败时停止所有操作(谢谢@andss)。
注意:这有无限的潜在变化。我试图让这个答案简短明了,但请在评论中提出建议!
我最近一直在用pur。这很简单,切中要害。它会更新您的requirements.txt文件以反映升级,然后您可以像往常一样使用requirements.txt文件进行升级。
$ pip install pur
...
Successfully installed pur-4.0.1
$ pur
Updated boto3: 1.4.2 -> 1.4.4
Updated Django: 1.10.4 -> 1.10.5
Updated django-bootstrap3: 7.1.0 -> 8.1.0
All requirements up-to-date.
$ pip install --upgrade -r requirements.txt
Successfully installed Django-1.10.5 ...
我在pip问题讨论中找到的最简单、最快的解决方案是:
pip install pipdate
pipdate
资料来源:https://github.com/pypa/pip/issues/3819
以下是通过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)