Python教程

python自动升级三方库

本文主要是介绍python自动升级三方库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import subprocess
# 由于pip内置对象已失效,自己做了一个自动升级三方库的脚本
# from pip._internal.utils.misc import get_installed_distributions

# 备份三方文件放到桌面
# call("pip freeze > requirements.txt", shell=True)
# 三方文件直接安装
# call("sudo pip install -r requirements.txt", shell=True)


def read_outdated(order="pip list -o"):
    # 罗列所有的三方库
    status, pip_list_outdated = subprocess.getstatusoutput(order)
    # TODO 写个筛选
    if status == 0:
        # 空格分割一次
        pip_list_outdated = pip_list_outdated.split()[8::]
        if len(pip_list_outdated) != 0:
            # 等差取值
            app_number = len(pip_list_outdated) / 4
            app_list = []
            for i in range(int(app_number)):
                app_list.append(pip_list_outdated[i * 4])
            return app_list
        else:
            return None
    else:
        print("命令有问题!")
        sys.exit()


def app_upgrade(app_list=None):
    # pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade 换清华镜像升级第三方库
    for app in app_list:
        subprocess.Popen(
            "pip install -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com --upgrade "
            + app,
            shell=True,
        ).wait()
    subprocess.Popen(
        "python -m pip install --upgrade pip -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com",
        shell=True).wait()


if __name__ == '__main__':
    app_list = read_outdated()
    if app_list is not None:
        app_upgrade(app_list)

这篇关于python自动升级三方库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!