UOS+Python+PyQt5(兆芯和飞腾)平台,实S4测试(图形界面)

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'System_S4_Test.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


import configparser
import json
import logging
import os
import platform
import shutil
import subprocess
import sys
import time
import datetime


import requests
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QMetaObject, Qt
from PyQt5.QtWidgets import QWidget, QApplication,QMessageBox


class System_S4_Test(QWidget):
    # 定义颜色代码
    COLOR_SUCCESS = "\033[1;32;43m"
    COLOR_ERROR = "\033[1;31m"
    COLOR_RESET = "\033[0m"

    def __init__(self):
        super().__init__()
        self.setupUi()
        self.testArgs = []  # 测试参数信息
        self.itemName = ''  # 项目名称
        self.testStandardArgs = ''  # 测试标准参数
        self.SN = ''  # 获取SN条码信息
        self.Product_name = ''  # 产品名称
        self.Process_name = ''  # 工序名称
        self.TestWebApi = 'N/A'  # 测试WebApi接口
        self.elapsed_time=20
        self.testcount=1#测试次数
        self.system_name = ''  # 系统环境
        self.cpu_architecture = ''  # CPU框架
        self.logger = None
        self.config = None

        self.loggerrinfo()  # 创建日志信息
        self.GetitemName()  # 获取项目名称
        # self.Get_BarcodeNo()#获取条码信息
        self.gather_log_upload_data()  # 获取产品名称、工序名称、SN条码信息

        # 读取系统信息
        self.system_name = self.get_system_name().lower()
        # 读取CPU框架
        self.cpu_architecture = self.get_cpu_architecture()

        # 读取配置
        self.config.read('./Conf/config.conf', encoding='utf-8')  # 读取配置文件,如果配置文件不存在则创建

        # 读取Test_WebApi接口配置
        self.TestWebApi = self.config.get('TestWepApi', 'url')

        # 获取参数信息
        if self.ReadJsonTestArgs() == True:
            self.lbl_readargs.setText(f'{self.testStandardArgs}次')
            self.progressBar.setMaximum(int(self.testStandardArgs))  # 设置进度条的最大值
            self.lcdNumber.display(self.testcount)  # 显示在LCD数码管
            self.progressBar.setValue(self.testcount)  # 更新进度条

            self.timer = QTimer(self)  # 创建定时器
            self.timer.timeout.connect(self.update_time)  # 定时器超时连接到更新时间的槽函数
            self.elapsed_time = 20  # 初始化经过时间
            self.timer.start(1000)  # 每1000毫秒(即每秒)触发一次
        else:
            self.ShowLog(f"Read {self.itemName} Test Args Fail!!", False)
            sys.exit(1)


    def setupUi(self):
        self.setObjectName("Form")
        self.resize(895, 229)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Conf/ICON/System_S4_Test.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)

        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.lbl_logo = QtWidgets.QLabel(self)
        self.lbl_logo.setText("")
        self.lbl_logo.setPixmap(QtGui.QPixmap("IMAGE/logo.jpg"))
        self.lbl_logo.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_logo.setObjectName("lbl_logo")
        self.verticalLayout_2.addWidget(self.lbl_logo)
        self.lbl_Title = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.lbl_Title.setFont(font)
        self.lbl_Title.setStyleSheet("background-color: rgb(85, 255, 127);\n"
"color: rgb(85, 85, 127);")
        self.lbl_Title.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Title.setObjectName("lbl_Title")
        self.verticalLayout_2.addWidget(self.lbl_Title)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.label_3 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(13)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_3.addWidget(self.label_3)
        self.lbl_readargs = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_readargs.setFont(font)
        self.lbl_readargs.setStyleSheet("color: rgb(255, 170, 0);")
        self.lbl_readargs.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_readargs.setObjectName("lbl_readargs")
        self.verticalLayout_3.addWidget(self.lbl_readargs)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_5 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.label_5.setFont(font)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.verticalLayout_4.addWidget(self.label_5)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.lcdNumber = QtWidgets.QLCDNumber(self)
        self.lcdNumber.setObjectName("lcdNumber")
        self.horizontalLayout_4.addWidget(self.lcdNumber)
        self.label = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.horizontalLayout_4.addWidget(self.label)
        self.horizontalLayout_4.setStretch(0, 9)
        self.horizontalLayout_4.setStretch(1, 1)
        self.verticalLayout_4.addLayout(self.horizontalLayout_4)
        self.horizontalLayout.addLayout(self.verticalLayout_4)
        self.horizontalLayout.setStretch(0, 4)
        self.horizontalLayout.setStretch(1, 3)
        self.horizontalLayout.setStretch(2, 3)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.lbl_showinfo = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.lbl_showinfo.setFont(font)
        self.lbl_showinfo.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_showinfo.setObjectName("lbl_showinfo")
        self.horizontalLayout_2.addWidget(self.lbl_showinfo)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.progressBar = QtWidgets.QProgressBar(self)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_3.addWidget(self.progressBar)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.verticalLayout.setStretch(0, 5)
        self.verticalLayout.setStretch(1, 4)
        self.verticalLayout.setStretch(2, 1)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)  # 只显示最小化按钮和关闭按钮

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Form", "System 【S4】测试"))
        self.lbl_Title.setText(_translate("Form", "System 【S4】测试"))
        self.label_3.setText(_translate("Form", "配置次数"))
        self.lbl_readargs.setText(_translate("Form", "N/A"))
        self.label_5.setText(_translate("Form", "已完成测试次数"))
        self.label.setText(_translate("Form", "次"))
        self.lbl_showinfo.setText(_translate("Form", "System S4测试中..."))

    # 定义一个函数使得函数窗口居中显示
    def Center(self):
        # 获取屏幕尺寸
        screen_geometry = app.desktop().availableGeometry()
        # 计算窗口居中位置
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        # 设置窗口位置
        self.move(x, y)

    # 使用os库检测系统名称
    def get_system_name(self):
        try:
            with open("/etc/os-release") as f:
                for line in f:
                    if line.startswith("NAME="):
                        # 移除行中的"NAME="和可能的引号
                        return line.strip().replace('NAME=', '').replace('"', '')
        except FileNotFoundError:
            pass
        return "Unknown"

    def get_cpu_architecture(self):
        # 使用platform库检测CPU架构
        arch = platform.machine()
        # 简化为常用架构名称
        if arch in ['x86_64']:
            return 'x86_64'
        elif arch in ['arm', 'arm64', 'aarch64']:
            return 'arm'
        else:
            return 'unknown'

    # 日志信息
    def loggerrinfo(self):
        try:
            # 确保日志文件的目录存在
            log_directory = './log'
            if not os.path.exists(log_directory):
                os.makedirs(log_directory)

            self.config = configparser.ConfigParser()  # 创建配置解析器对象
            # 生成日志信息
            self.logger = logging.getLogger('my_logger')  # 创建日志记录器
            self.logger.setLevel(logging.DEBUG)  # 设置日志级别为DEBUG
            file_handler = logging.FileHandler(f'{log_directory}/log.txt')  # 创建文件处理器
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 创建格式化器
            file_handler.setFormatter(formatter)  # 将格式化器设置到文件处理器
            self.logger.addHandler(file_handler)  # 将文件处理器添加到日志记录器
        except Exception as e:
            self.ShowLog(f'Create logger_info Error: {str(e)}', False)

    # 处理S4日志文件并上传
    def process_s4logfile_upload(self):
        try:
            copied_log_file = f"{self.SN}_S4.log"
            if self.check_log_file_exists(copied_log_file):
                # 尝试上传文件
                upload_url = f"{self.TestWebApi}/TestLog/uploadTestLog"
                if not self.upload_test_log(upload_url, self.Product_name, f'{self.Process_name}/S4',
                                            copied_log_file):
                    self.ShowLog('Failed to upload test log', False)
                    return False

                # 文件上传成功后删除原始文件
                self.delete_file(copied_log_file)
                return True
            else:
                self.ShowLog(f'{copied_log_file} Log file does not exist', False)
                return False
        except Exception as e:
            self.ShowLog(f'process s4 logfile upload Err:{str(e)}', False)
            sys.exit(1)

    # 查找当前目录文件是否存在
    def check_log_file_exists(self, filename):
        # 获取当前工作目录
        current_directory = os.getcwd()
        # 构造文件的完整路径
        file_path = os.path.join(current_directory, filename)
        # 检查文件是否存在
        return os.path.exists(file_path)

    # 装载订单信息
    def load_order_info(self, filepath='./Conf/OrderInfo.json'):
        try:
            with open(filepath, 'r') as file:
                data = json.load(file)
                return {item: value for dic in data for item, value in dic.items()}
        except FileNotFoundError:
            self.ShowLog("File not found. Please check the filepath.", False)
            sys.exit(1)
        except json.JSONDecodeError:
            self.ShowLog("Error decoding JSON. Please check the file format.", False)
            sys.exit(1)

    # 获取日志上传基础信息
    # 蛇形命名法(snake_case)
    def gather_log_upload_data(self):
        order_info = self.load_order_info()
        if order_info is None:
            self.ShowLog("Failed to load order info, aborting update.", False)
            sys.exit(1)

        # Extract needed information
        self.SN = order_info.get("SN", "Not Found")
        self.Process_name = order_info.get("NextWorkStation", "Not Found")
        self.Product_name = order_info.get("ItemDesc", "Not Found")

        if self.SN == "Not Found" or self.Process_name == "Not Found" or self.Product_name == "Not Found":
            self.ShowLog("Required information is missing from the order info.", False)
            sys.exit(1)
        return True

    # 上传测试日志
    def upload_test_log(self, url, product_name, process_name, file_path):
        """
        上传测试日志文件到指定的 Web API。

        :param url: Web API 的 URL。
        :param product_name: 产品名称。
        :param process_name: 测试过程名称。
        :param file_path: 要上传的日志文件的路径。
        :return: 返回响应对象。
        """

        # 设置查询参数
        params = {
            "productName": product_name,
            "processName": process_name
        }

        # 打开要上传的文件
        with open(file_path, 'rb') as file:
            # 设置请求体中的文件部分
            files = {
                "logfile": (file_path, file, "application/json")
            }

            # 发送 POST 请求
            response = requests.post(url, params=params, files=files)
            if response.status_code == 200:
                self.ShowLog("Test log file uploaded successfully.", True)
                self.delete_file(file_path)  # 删除上传文件
                return True
            else:
                self.ShowLog(
                    f"Failed to upload test log file. Status code: {response.status_code}, Response: {response.text}",
                    False)
                sys.exit(1)

    # 时钟计时
    def update_time(self):
        if self.testcount > int(self.testStandardArgs):
            self.timer.stop()  # 停止定时器
            self.lbl_showinfo.setText("S4测试完成!")
            self.UpdateJsonTestArgs(self.itemName, self.testStandardArgs, "PASS")
            self.process_s4logfile_upload()  # 上传S4日志
            sys.exit(0)
        else:
            if self.elapsed_time <= 0:
                self.timer.stop()  # 停止定时器
                self.testcount+=1
                self.lcdNumber.display(self.testcount)  # 显示在LCD数码管
                self.progressBar.setValue(self.testcount)  # 更新进度条
                self.lbl_showinfo.setText("倒计时结束,开始S4测试。")
                self.perform_s4_sleep_test(self.testcount)#开始S4测试
            else:
                self.elapsed_time -= 1  # 秒数加1
                self.lbl_showinfo.setText(f"倒计时: {self.elapsed_time} 秒,开始S4测试!!")

            # self.ShowLog("Aging test completed successfully.", True)

    # 执行S4睡眠测试
    def perform_s4_sleep_test(self, num):
        try:
            if self.cpu_architecture == 'arm':
                # 检查休眠触发是否被启用
                with open(f"./{self.SN}_S4.log", "a") as log_file:
                    subprocess.run(['sh', '-c', 'echo reboot > /sys/power/disk'])
                    subprocess.run(['sh', '-c', 'echo disk > /sys/power/state'])
                    log_entry = f"第{datetime.datetime.now()} {num}次测试……\n"
                    log_file.write(log_entry)
                    self.timer.start()  # 启动定时器
                    self.elapsed_time = 20  # 次
            else:
                # 检查休眠触发是否被启用
                with open("/sys/class/rtc/rtc0/device/power/wakeup", "r") as file:
                    status = file.read().strip()
                    if status == "disabled":
                        subprocess.run(['sudo', 'sh', '-c', 'echo enabled > /sys/class/rtc/rtc0/device/power/wakeup'])
                with open(f"./{self.SN}_S4.log", "a") as log_file:
                    # 使计算机进入S4休眠模式并记录系统消息
                    subprocess.run(['sudo', 'rtcwake', '-l', '-m', 'disk', '-s', '60'])
                    result = subprocess.run(['sudo', 'dmesg'], capture_output=True, text=True)
                    errors = subprocess.run(['egrep', "error|failed|warning"], input=result.stdout, capture_output=True, text=True)
                    log_entry = f"第{datetime.datetime.now()} {num}次测试……\n{errors.stdout}"
                    log_file.write(log_entry)
                    self.timer.start()  # 启动定时器
                    self.elapsed_time = 20  # 次
        except Exception as e:
            self.ShowLog(f'perform_4_sleep_test Err:{str(e)}', False)
            return False
        return True

    # 删除当前目录下指定文件
    def delete_file(self, filename):
        # 获取当前工作目录的完整路径
        full_path = os.path.join(os.getcwd(), filename)

        # 检查文件是否存在于当前工作目录
        if os.path.exists(full_path):
            # 删除文件
            os.remove(full_path)
            print(f"{filename} has been deleted from the current directory.")
        else:
            # 如果文件不存在,打印一个消息
            print(f"The file {filename} does not exist in the current directory.")

    # 获取项目名称
    def GetitemName(self):
        try:
            # 获取当前执行文件的完整路径
            full_path = sys.argv[0]
            # 从完整路径中提取文件名
            file_name = os.path.basename(full_path)
            self.itemName = file_name  # 项目名称
        except Exception as e:
            self.ShowLog(f'Get Item Name Err:{str(e)}', False)

    # 读取json信息,fileName:文件名称
    def ReadJsonInfo(self, fileName):
        try:
            if os.path.exists(fileName):
                f = open(fileName, 'r', encoding='utf-8')
            return json.loads(f.read())
        except Exception as e:
            self.ShowLog("Read " + fileName + " Err:" + str(e), False)
            sys.exit(1)

    # 读取项目参数信息,itemName:项目名称
    def ReadJsonTestArgs(self):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                print(self.itemName, js['ItemScript'])
                if self.itemName in js['ItemScript']:
                    self.testStandardArgs = js['Standard']
                    return True
            return False
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + self.itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    # 更新测试参数json,itemName:项目名称,readValue:读取值,testResult:测试结果
    def UpdateJsonTestArgs(self, itemName, readValue, testResult):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            if self.testArgs is None:
                raise Exception("Failed to read configuration, aborting update.")

            for js in self.testArgs:
                if itemName in js['ItemScript']:
                    js['Read'] = readValue
                    js['TestResult'] = testResult

            with open("./Conf/TestArgs.json", "w") as write_file:
                json.dump(self.testArgs, write_file, indent=4)  # Use indent for pretty printing

            return True
        except Exception as e:
            self.ShowLog(f"Update TestArgs.json ItemName: {itemName} Info Err: {str(e)}", False)
            sys.exit(1)

    # 获取SN条码信息
    def Get_BarcodeNo(self):
        try:
            # 使用 with 语句确保文件被正确关闭
            with open('./Conf/OrderInfo.json', 'r') as file:
                self.testArgs = json.load(file)
            if self.testArgs is None:
                raise Exception("Failed to read ./Conf/OrderInfo.json, aborting update.")
            self.SN = next((item.get("SN") for item in self.testArgs if "SN" in item), "Not Found")
            if self.SN is None or self.SN == 'Not Found':
                return False
            print(self.SN)
            return True
        except Exception as e:
            self.ShowLog(f"读取条码信息错误: {str(e)}", False)
            sys.exit(1)

    # 写fail.txt文件信息
    def write_to_file(self, fileName, text):
        try:
            # 获取当前工作目录的完整路径
            # full_path = os.path.join(os.getcwd(), fileName)
            # if os.path.exists(full_path):
            #     return True
            # 使用'w'模式打开文件,每次调用此函数都会覆盖原有内容
            with open(fileName, 'w') as file:
                file.write(text)

            # 修改文件权限为777
            os.chmod(fileName, 0o777)
            return True
        except Exception as e:
            self.ShowLog(f"Create or modify {fileName} file failed: {str(e)}", False)
            sys.exit(1)

    # def enable_auto_login(self,username=None, lightdm_conf_path="/etc/lightdm/lightdm.conf"):
    #     """
    #     启用自动登录
    #
    #     参数:
    #     username: 要自动登录的用户名,默认为当前用户
    #     lightdm_conf_path: lightdm 配置文件的路径
    #     """
    #     if username is None:
    #         username = os.getlogin()  # 获取当前登录的用户名
    #
    #     try:
    #         # 检查文件是否存在
    #         if not os.path.exists(lightdm_conf_path):
    #             print(f"配置文件 {lightdm_conf_path} 不存在。")
    #             return False
    #
    #         # 读取配置文件内容
    #         with open(lightdm_conf_path, 'r') as file:
    #             lines = file.readlines()
    #
    #         # 修改配置文件以启用自动登录
    #         with open(lightdm_conf_path, 'w') as file:
    #             autologin_found = False
    #             for line in lines:
    #                 if "autologin-user=" in line:
    #                     line = f"autologin-user={username}\n"
    #                     autologin_found = True
    #                 file.write(line)
    #             if not autologin_found:
    #                 file.write(f"autologin-user={username}\n")
    #         print("自动登录已启用。")
    #         return True
    #     except Exception as e:
    #         print(f"发生错误:{e}")
    #         return False
    #
    # def disable_auto_login(slef,lightdm_conf_path="/etc/lightdm/lightdm.conf"):
    #     """
    #     取消自动登录
    #
    #     参数:
    #     lightdm_conf_path: lightdm 配置文件的路径
    #     """
    #     try:
    #         # 检查文件是否存在
    #         if not os.path.exists(lightdm_conf_path):
    #             print(f"配置文件 {lightdm_conf_path} 不存在。")
    #             return False
    #
    #         # 读取配置文件内容
    #         with open(lightdm_conf_path, 'r') as file:
    #             lines = file.readlines()
    #
    #         # 修改配置文件以取消自动登录
    #         with open(lightdm_conf_path, 'w') as file:
    #             for line in lines:
    #                 if "autologin-user=" not in line:
    #                     file.write(line)
    #         print("自动登录已禁用。")
    #         return True
    #     except Exception as e:
    #         print(f"发生错误:{e}")
    #         return False

    def enable_auto_login(self, username=None, lightdm_conf_path="/etc/lightdm/lightdm.conf"):
        """
        启用自动登录

        参数:
        username: 要自动登录的用户名,默认为当前用户
        lightdm_conf_path: lightdm 配置文件的路径
        """
        if username is None:
            username = os.getlogin()  # 获取当前登录的用户名

        try:
            # 检查文件是否存在
            if not os.path.exists(lightdm_conf_path):
                print(f"配置文件 {lightdm_conf_path} 不存在。")
                return False

            # 读取配置文件内容
            with open(lightdm_conf_path, 'r') as file:
                lines = file.readlines()

            # 修改配置文件以启用自动登录
            with open(lightdm_conf_path, 'w') as file:
                autologin_found = False
                for line in lines:
                    if "autologin-user=" in line:
                        line = f"autologin-user={username}\n"
                        autologin_found = True
                    file.write(line)
                if not autologin_found:
                    file.write(f"autologin-user={username}\n")
            print("自动登录已启用。")
            return True
        except Exception as e:
            print(f"发生错误:{e}")
            return False

    def disable_auto_login(slef, lightdm_conf_path="/etc/lightdm/lightdm.conf"):
        """
        取消自动登录

        参数:
        lightdm_conf_path: lightdm 配置文件的路径
        """
        try:
            # 检查文件是否存在
            if not os.path.exists(lightdm_conf_path):
                print(f"配置文件 {lightdm_conf_path} 不存在。")
                return False

            # 读取配置文件内容
            with open(lightdm_conf_path, 'r') as file:
                lines = file.readlines()

            # 修改配置文件以取消自动登录
            with open(lightdm_conf_path, 'w') as file:
                for line in lines:
                    if "autologin-user=" not in line:
                        file.write(line)
            print("自动登录已禁用。")
            return True
        except Exception as e:
            print(f"发生错误:{e}")
            return False

    # 打印的信息
    def ShowLog(self, log, isPass):
        try:
            if isPass == True:
                print("\033[1;32;43m" + str(log) + " \033[0m")
                self.logger.info(str(log))
            else:
                print("\033[1;31m" + str(log) + " \033[0m")
                self.logger.error(str(log))
        except Exception as e:
            print("\033[1;31m" + str(e) + " \033[0m")
            sys.exit(1)


    # 手动关闭窗口
    def closeEvent(self, event):
        # 创建一个消息框,上面有两个按钮:“是”和“否”
        # reply = QMessageBox.question(self, '退出', "你确定要退出吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        # 如果用户点击了“是”,则执行event.accept()来关闭窗口
        # if reply == QMessageBox.Yes:
        #    event.accept()
        #    sys.exit(1)
        # else:
        # 如果用户点击了“否”,则忽略event,不关闭窗口
        #    event.ignore()
        sys.exit(1)

if __name__=='__main__':
    app=QApplication(sys.argv)
    win=System_S4_Test()
    win.Center()  # 居中
    win.show()
    sys.exit(app.exec_())

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值