【发布时间】:2021-08-06 03:27:34
【问题描述】:
我正在尝试在 Python 3.7.3 中使用 web-socket 和 pyqt5 构建一个小型应用程序。基本上,我使用两个网络套接字,一个用于触发唤醒词,另一个用于获取意图。我想将此意图数据(JSON 格式)传递给工作线程,该工作线程将进一步检查条件类型,然后在主 GUI 上显示适当的输出。在这里,用户的输入本质上可以是连续的,也可以不是连续的,但无论输入是否来自用户,GUI 和两个 web-socket 都应该连续并行运行。
# Intents are passed through here
def on_message(ws, message):
data = json.loads(message)
return data
def on_error(ws, error):
print("Error from Intent",error)
def on_close(ws):
print("**Disconnected**")
def on_open(ws):
print("**Connected**")
# Same way for Wake Word as did above
#GUI starts here
frame_less = QtCore.Qt.WindowFlags(QtCore.Qt.FramelessWindowHint)
#GUI Thread class
class ExecuteThread(QThread):
# creating signals
output_signal = pyqtSignal(str)
finished = pyqtSignal()
def run(self):
self.process_intent()
#checking intent name and executing respective action
def process_intent(self):
while True:
#intent method is being called
self.intent = on_message()
if ("GetTime" == self.intent["intent"]["name"]):
say('GetTime Intent Recognized') #text to speech method
self.output_signal.emit('GetTime Intent Recognized\n') #should display on GUI
QThread.msleep(3000)
self.finished.emit()
elif:
#do somthing here as above
else:
say('Please Try again') #text to speech method
self.output_signal.emit('Please Try again') #should display on GUI
QThread.msleep(3000)
self.finished.emit()
load_gui,_ = loadUiType('virtual_gui.ui')
#GUI main class
class Main(QMainWindow,load_gui):
def __init__(self,parent=None):
super(Main,self).__init__(parent)
self.setupUi(self)
self.setFixedSize(1200,800)
# some other stuff
#Starting Main Event Funaction
self.Start_Main_Event()
def Start_Main_Event(self):
self.thread = ExecuteThread()
#connecting signals to respective functions
self.thread.output_signal.connect(self.output_event)
self.thread.finished.connect(self.thread_finished)
self.thread.start()
def thread_finished(self):
# gets executed if thread finished
self.text_output.setText('')
print('finished')
def output_event(self,text):
# gets executed on signal
self.text_output.setText(text)
#displaying gui function
def main_class():
App = QApplication(sys.argv)
win = Main()
win.show()
win.showFullScreen ()
QtWidgets.QApplication.setQuitOnLastWindowClosed(True)
App.aboutToQuit.connect(App.deleteLater)
App.exec_()
App.quit()
# Start web socket client and gui
if __name__ == "__main__":
ws = websocket.WebSocketApp("ws://localhost/intent",
on_message = on_message,
on_error = on_error,
on_close = on_close,
on_open = on_open)
wake = websocket.WebSocketApp("ws://localhost/wake-word",
on_message = on_Message,
on_error = on_Error,
on_close = on_Close,
on_open = on_Open)
t1 = Thread(target = ws.run_forever)
t2 = Thread(target = wake.run_forever)
# start gui
t3 = Thread(target = main_class())
# starting threads
t1.start()
t2.start()
t3.start()
# wait until all threads finish
t1.join()
t2.join()
t3.join()
print ("Exiting Main Thread")
【问题讨论】:
标签: python multithreading websocket pyqt pyqt5