# -*- coding: utf-8 -*-
# Name: demo.py
# Author: 小菜
# Date: 2023/5/4
# Description:
import sys
from engineTelnet import WorkerTelnetProxy
from PySide6.QtCore import (QThread, QWaitCondition, QMutex, Signal, QMutexLocker)
class MyThread(QThread):
valueChange = Signal(int)
def __init__(self, parent=None):
super().__init__(parent=parent)
self.is_paused = bool(0) # 标记线程是否暂停
self.progress_value = int(0) # 进度值
self.mutex = QMutex() # 互斥锁,用于线程同步
self.cond = QWaitCondition() # 等待条件,用于线程暂停和恢复
self.telnet = WorkerTelnetProxy()
self.log = ""
self.cmds = None
# def pause_thread(self):
# with QMutexLocker(self.mutex):
# self.is_paused = True # 设置线程为暂停状态
#
# def resume_thread(self):
# if self.is_paused:
# with QMutexLocker(self.mutex):
# self.is_paused = False # 设置线程为非暂停状态
# self.cond.wakeOne() # 唤醒一个等待的线程
def setCmd(self,cmds):
self.cmds = cmds
def getLog(self):
return self.log
def stop(self):
self.telnet.destroyEngine()
def run(self):
try:
res = self.telnet.start()
except Exception as e:
self.log = str(e)+"\ntelnet connect fail!" + "\n" +"please check telnet \n"
self.valueChange.emit(100000)
return False
self.log = None
for cmd in self.cmds:
print("into the cmd command!\n")
#self.log += str(cmd)
print("the cmd is :{}\n".format(cmd))
response = self.telnet.startcmd(cmd)
self.log = str(cmd) +":\n" +str(response)+"\n"
self.valueChange.emit(1)
self.cmds = []
self.valueChange.emit(100000)
将方法封装在thread类中.
因为使用到telnet的交互会产生阻塞,如果放在主窗口中进行调用,会出现主窗口在telnet的阻塞的时候发生卡住。现在将这一部分放在thread的 run方法中。在使用thread.start()进行方法的调用,让telnet自己在线程中去跑,在跑完后通过信号量的发送,将结果在取回。这样处理掉了主窗口因为阻塞而卡顿的问题