是否可以使用pip一次性升级所有Python包?
注意:官方问题跟踪器上对此有一个功能请求。
是否可以使用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)
我接受了拉玛纳的回答,并使其变得友好。
其他回答
拉玛纳的回答对我来说是最好的,但我不得不补充几点:
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)。
以下命令在Windows上运行,对其他人也很有用($是命令提示符下的任何目录。例如,C:\Users/Username)。
Do
$ pip freeze > requirements.txt
打开文本文件,将==替换为>=,或让sed为您执行以下操作:
$ sed -i 's/==/>=/g' requirements.txt
并执行:
$ pip install -r requirements.txt --upgrade
如果您对某个软件包延迟升级有问题(有时是NumPy),只需转到目录($),注释掉名称(在其前面添加#),然后再次运行升级。稍后可以取消注释该部分。这对于复制Python全局环境也非常有用。
另一种方式:
我也喜欢pip审查方法:
py2
$ pip install pip-review
$ pip-review --local --interactive
py3
$ pip3 install pip-review
$ py -3 -m pip-review --local --interactive
您可以选择“a”来升级所有软件包;如果一次升级失败,请再次运行,然后在下一次升级中继续。
要在默认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'))
这是Python 3的PowerShell解决方案:
pip3 list --outdated --format=legacy | ForEach { pip3 install -U $_.split(" ")[0] }
对于Python 2:
pip2 list --outdated --format=legacy | ForEach { pip2 install -U $_.split(" ")[0] }
这将逐个升级软件包。因此
pip3 check
pip2 check
之后应该确保没有中断依赖关系。
Use:
pip install -r <(pip freeze) --upgrade