是否可以使用pip一次性升级所有Python包?
注意:官方问题跟踪器上对此有一个功能请求。
是否可以使用pip一次性升级所有Python包?
注意:官方问题跟踪器上对此有一个功能请求。
当前回答
这似乎更简洁。
pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U
说明:
pip-list——过时的代码行如下
urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]
在cut-d“”-f1中,-d“”将“空格”设置为分隔符,-f1表示获取第一列。
因此,上述行变为:
urllib3
wheel
然后将它们传递给xargs以运行命令pipinstall-U,每一行都作为附加参数
-n1将传递给每个命令pip install-U的参数数限制为1
其他回答
要在默认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'))
在我看来,这个选项更简单易懂:
pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`
解释是,pip-list——过时输出所有过时包的列表,格式如下:
Package Version Latest Type
--------- ------- ------ -----
fonttools 3.31.0 3.32.0 wheel
urllib3 1.24 1.24.1 wheel
requests 2.20.0 2.20.1 wheel
在awk命令中,NR>2跳过前两条记录(行),{print$1}选择每行的第一个单词(正如SergioAraujo所建议的,我删除了tail-n+3,因为awk确实可以处理跳过记录)。
这里有一个脚本,它只更新过时的包。
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)
您可以只打印过期的软件包:
pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:'
下面是用Python编写脚本的另一种方法:
import pip, tempfile, contextlib
with tempfile.TemporaryFile('w+') as temp:
with contextlib.redirect_stdout(temp):
pip.main(['list', '-o'])
temp.seek(0)
for line in temp:
pk = line.split()[0]
print('--> updating', pk, '<--')
pip.main(['install', '-U', pk])