使用/ as时需要线程化的最佳方法(python,pyqt)

时间:2017-07-13 11:31:46

标签: python pyqt qthread

我试图使用qthread运行一个worker类。如果使用workerObject = workerClass()实例化worker,我可以毫无问题地执行此操作。如果工人类需要始终执行退出

,我该怎么做呢?

以下是尝试执行此操作的示例代码。不幸的是,通过运行它,退出函数不会被执行,很可能这是因为线程不知道with / as语句

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import sys
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.textEdit = QtGui.QTextEdit(Dialog)
        self.textEdit.setGeometry(QtCore.QRect(20, 20, 361, 191))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(170, 250, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "Print", None))



class UI_MainWindow(QtGui.QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(UI_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.run)


    def run(self):
        self.t = QThread()
        self.x = None
        with worker() as self.x:        
            self.x.signal.connect(self.write)
            self.x.moveToThread(t) 
            t.started.connect(self.x.run)
            t.start()

    @pyqtSlot(str)
    def write(self, text):
        self.textEdit.append("Running")
        qtObject.processEvents()




class worker(QObject):
    signal = pyqtSignal(str)

    def __init__(self, parent = None):
        super(worker, self).__init__(parent)

    def __enter__(self):
        return self

    def run(self):
        self.signal.emit("Running")
        time.wait(5)
        raise Exception

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.signal.emit("Exception")




def main(qtObject, guiObj):
    guiObj.show()
    qtObject.exec_()
    qtObject.processEvents()


qtObject = QtGui.QApplication(sys.argv)
guiObj = UI_MainWindow()
main(qtObject, guiObj)

LE:上下文涉及需要在QTextEdit窗口中打印来自worker类的任何失败消息。在worker类执行期间引发的任何异常都在其exit函数中处理,这样无论发生什么错误,脚本都会优雅地为用户提供有意义的信息和指令。

2 个答案:

答案 0 :(得分:0)

__exit__函数 执行 执行,问题是由于线程的非阻塞性质,with构造立即在工人"完成之前终止(调用worker.__exit__)"并提出异常。

实现所需目标的一种方法是使用worker.run()语句将try/except中的代码包围起来,以捕获任何未处理的异常并执行任何清理或发出信号。

def run(self):
    try:
        self.signal.emit("Running")
        time.sleep(5)
        raise Exception
    except:
        self.signal.emit("Exception")

答案 1 :(得分:0)

从user3419537解决方案开始,我已经完成了以下解决方案。第二个信号(statusSignal)用于将所有与异常相关的信息传回主类,以便可以调用exit函数。

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import sys
import time

class err(Exception):
    def __init__(self, *args):
        self.args = [a for a in args]

mainThread = QtCore.QThread.currentThread()

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.textEdit = QtGui.QTextEdit(Dialog)
        self.textEdit.setGeometry(QtCore.QRect(20, 20, 361, 191))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(170, 250, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "Print", None))



class UI_MainWindow(QtGui.QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(UI_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.run)

    def run(self):
        self.t = QThread()
        self.x = worker()          
        self.x.signal.connect(self.write)
        self.x.statusSignal.connect(self.runExit)
        self.x.moveToThread(self.t) 
        self.t.started.connect(self.x.run)
        self.t.start()

    @pyqtSlot(str)
    def write(self, text):
        self.textEdit.append(text)
        qtObject.processEvents()

    @pyqtSlot(object, object, object)
    def runExit(self, exc_type, exc_value, exc_traceback):
        self.t2 = QThread()
        self.x.moveToThread(self.t2)
        self.t2.started.connect(lambda: self.x.__exit__(exc_type, exc_value, exc_traceback))
        self.t2.start()






class worker(QObject):
    signal = pyqtSignal(str)
    statusSignal = pyqtSignal(object, object, object)

    def __init__(self, parent = None):
        super(worker, self).__init__(parent)

    def run(self):
        try:
            self.signal.emit("Run")
            time.sleep(2)
            self.moveToThread(mainThread)
            raise err("err message")
        except err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.statusSignal.emit(exc_type, exc_value, exc_traceback)

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.signal.emit(exc_value.args[0])



def main(qtObject, guiObj):
    guiObj.show()
    qtObject.exec_()
    qtObject.processEvents()


qtObject = QtGui.QApplication(sys.argv)
guiObj = UI_MainWindow()
main(qtObject, guiObj)

最有可能仍然会对代码进行一些调整,但就目前而言,它完美无缺。