更新时间:2022-08-12 11:26:34

问题描述:安装离线proton-cs的时候,安装脚本默认支持是python2,在python3环境下安装会有部分不兼容。

解决方法:根据本问题的步骤进行操作即可解决。

1.先试用命令
ls 查看proton安装包,我们将安装脚本记为 installScript 。再使用 rm -f installScript 删除原安装包当中的脚本。


2.使用命令 vi installScript,创建新的安装脚本


3.按键盘a字母键,使得操作变为插入模式。


4.粘贴如下命令到文件当中。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
说明:系统依赖的本地安装脚本
"""

import os
import re
import sys
import shutil
import inspect
import subprocess



def script_path():
    """
    function: get absolute directory of the file
        in which this function defines
    usage: path = script_path()
    note: please copy the function to target script,
        don't use it like .script_path()
    """
    this_file = inspect.getfile(inspect.currentframe())
    return os.path.abspath(os.path.dirname(this_file))
CURR_SCRIPT_PATH = script_path()

def shell_cmd(cmdstr):
    """
    /**
     * 执行命令,并等待返回结果
     * 命令执行出错,则抛出异常
     * 注意:执行时间较长或输出信息较多的命令,不建议使用此函数.
     *
     * @param cmdstr(str)               命令的完整字符串
     * @param timeout_seconds(int)      命令执行超时秒数设置
     *                                  若命令执行超过该秒数,则终止运行,并抛出超时异常
     *                                  不超时,请设置为None
     * @return(tuple(str, str))         返回命令执行的结果(outmsg, errmsg)
     * @raise(Exception)                命令执行失败将抛出异常
     */
    """
    (returncode, outmsg, errmsg) = shell_cmd_not_raise(cmdstr)
    if returncode != 0:
        error = "Run cmd failed.(CMD:%s)(RET:%s)(STDERR:%s)(STDOUT:%s)." % (
            cmdstr, returncode, errmsg, outmsg)
        raise Exception(error)

    # 返回命令输出
    return (outmsg, errmsg)

def shell_cmd_not_raise(cmdstr):
    """
    execute shell command not raise ex
    """
    try:
        process = subprocess.Popen(cmdstr,
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   close_fds=True)
    except Exception as ex:
        error = "Run cmd failed.(CMD:%s)(ERROR:%s)" % (cmdstr, ex)
        raise Exception(error)

    try:
        outmsg, errmsg = process.communicate(input=None)
        return (process.returncode, outmsg, errmsg)
    finally:
        if process:
            if process.stdin:
                process.stdin.close()
            if process.stdout:
                process.stdout.close()
            if process.stderr:
                process.stderr.close()


# ===============================================================================================
# 文件路径定义
# ===============================================================================================
# repo拷贝目录
REPO_DIR = '/tmp/repos'
CENTOS_YUM_DIR = '/etc/yum.repos.d'

def install_deps(proton_path, requirement_path):
    """初始化repo,创建本地yum源/挂载ISO源,安装依赖"""
    proton_repo = os.path.join(CENTOS_YUM_DIR, 'proton.repo')
    if os.path.exists(proton_repo):
        os.remove(proton_repo)
    config = get_major_version()
    config.add_section('proton')
    config.set('proton', 'name', 'CentOS-$releasever - Proton')
    config.set('proton', 'baseurl', 'file://' + REPO_DIR)
    config.set('proton', 'gpgcheck', '0')
    config.set('proton', 'enabled', '1')
    config.set('proton', 'gpgkey', 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7')
    config.write(open(proton_repo, "w"))

    # extract repository to /tmp/repos
    print("Extract proton repo to {0}".format(REPO_DIR))
    if os.path.isdir(REPO_DIR):
        shutil.rmtree(REPO_DIR)
    os.makedirs(REPO_DIR)
    shell_cmd("tar zxf {0} -C {1}".format(requirement_path, REPO_DIR))

    # install rpm deps
    print("Install proton rpm software start, more details in /var/log/messages.")
    ret, outmsg, errmsg = shell_cmd_not_raise("yum clean all;yum install {0} --disablerepo=* --enablerepo=proton -y".format(proton_path))
    if ret != 0:
        print(outmsg, errmsg)
        print(font_color("Install rpm software failed, please manual check later", "red"))
    else:
        print("Install proton rpm software ok.")

def get_major_version():
    import sys
    python_version = sys.version
    major = python_version.split(".")[0]
    if major == "3":
        import configparser
        return configparser.ConfigParser()
    else:
        import ConfigParser
        return ConfigParser.ConfigParser()

def get_kernel_version():
    """
    获取kernel版本,判断是否升级,需要重启
    """
    cmd = "rpm -q kernel"
    outmsg, errmsg = shell_cmd(cmd)
    return outmsg.strip()


def check_if_need_reboot(prev_kernel_version):
    """
    检查是否需要重启
    """
    # 升级前检查内核相关,更新后匹配版本是否一致,不一致则需重启
    cmd = "rpm -q kernel"

    outmsg, errmsg = shell_cmd(cmd)
    if outmsg.strip() == prev_kernel_version:
        return False
    else:
        print("The kernel has been updated and the system needs to be restarted.")
        return True


def font_color(string, color='white'):
    """
    设置文字颜色
    """
    if not string:
        return string

    color_dict = {
        'black' : 30,
        'red': 31,
        'green': 32,
        'yellow': 33,
        'blue': 34,
        'purple': 35,
        'cl': 36,
        'white': 37
    }
    color_code = color_dict[color]
    return '\033[1;%dm%s\033[0m' % (color_code, string)


def print_success_info(flag):
    """打印成功结束信息"""
    print(font_color('Install Deps successfully', 'green'))
    if flag:
        print(font_color('Warning: The system kernel has been updated, please manually restart the operating system later.', 'red'))


def main():
    print("============================[BEGIN]============================")

    # 获取当前路径下proton-xxx.rpm和依赖包路径
    proton_path = ''
    requirement_path = ''
    cur_dirs = os.listdir(script_path())
    for f in cur_dirs:
        if os.path.splitext(f)[1] == '.rpm' and f.startswith('proton-deps'):
            proton_path = os.path.join(script_path(), f)
        if os.path.splitext(f)[1] == '.gz' and f.startswith('proton-repository'):
            requirement_path = os.path.join(script_path(), f)


    # 获取update前kernel版本
    prev_kernel_version = get_kernel_version()

    # ========================安装系统依赖包=====================================
    print("Install proton deps package start.")
    install_deps(proton_path, requirement_path)

    # 检查是否需要重启(是否更新了内核)
    need_reboot = check_if_need_reboot(prev_kernel_version)

    # 打印结束信息
    print_success_info(need_reboot)

    print("============================[END]============================\n\n\n")


# =====================================================================
# 内部函数
# =====================================================================
if __name__ == '__main__':
    main()


5.按键盘的 ESC 退出插入模式,保存修改。如下图。保存完成之后,再使用原安装方式安装即可。