利用pip install –upgrade批量更新已过期的python库

Python有丰富的第三方库资源,并且第三方库更新速度也很快。但pip命令不支持全局全部库升级。我们可以通过pip编写python代码进行批量升级。查看系统里过期的python库,可以用pip命令:

pip list --outdated #列出所有过期的库

单个更新库名

pip install --upgrade 库名

在stackoverflow上有人提供了批量更新的办法,一个循环就搞定,代码如下:

#!/usr/bin/env python3

import pip
from subprocess import call
 
for dist in pip.get_installed_distributions():
    call("pip install --upgrade " + dist.project_name, shell=True)

其实自己写一个版本也不难,代码如下:

#!/usr/bin/env python3

import os
file = os.popen("pip list --outdated")
namelist = []
for line in file:
    data = line.split()
    namelist.append(data[0])
namelist = namelist[2:]
print("Available Packages:")
print(namelist)

for name in namelist:
    command = "pip install --upgrade " + name
    print(command)
    os.system(command)
print("PIP Upgrade Successfully")

Leave a Reply

Your email address will not be published. Required fields are marked *