在QThreadPool / QRunnable中停止信号以停止无限循环?

时间:2018-06-11 16:00:00

标签: python multithreading pyqt qt4

以下是运行2个可检查QPushButtons的代码。我想知道是否有任何优雅的方法可以在未经检查的情况下结束qrunnable中的循环?来自

的原始帮助

multithreading for simultaneous folder watching

import sys
import os
import time
import traceback

from PyQt4.QtGui import *
from PyQt4.QtCore import *


class SignalHelper(QObject):
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
    finished = pyqtSignal()

class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = SignalHelper()

    @pyqtSlot()
    def run(self):
        try:
            result = self.fn(*self.args, **self.kwargs)
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value,  
                                traceback.format_exc()))
        else:
            self.signals.result.emit(result)
        finally:
            self.signals.finished.emit()

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        layout = QVBoxLayout()

        path =  "Paths to watch"
        path2 = "Paths to watch"

        self.b = QPushButton("Button1")
        self.b.setCheckable(True)
        self.b.pressed.connect(lambda: self.watcher(path))

        self.b2 = QPushButton("Button1")
        self.b2.setCheckable(True)
        self.b2.pressed.connect(lambda: self.watcher(path2))

        layout.addWidget(self.b)
        layout.addWidget(self.b2)

        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        self.threadpool = QThreadPool()

    def watcher(self, s):
        worker = Worker(self.monitor, s)
        self.threadpool.start(worker)

    def monitor(self, s):
        before = dict([(f, None) for f in os.listdir(s)])
        while True:
            after = dict([(f, None) for f in os.listdir(s)])
            added = [f for f in after if not f in before]
            removed = [f for f in before if not f in after]
            if added: print("Added: ", ", ".join(added))
            if removed: print("Deleted: ", ", ".join(removed))
            before = after

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

不确定从QRunnable发出'kill'信号是否安全?或者,如果我只是将整个事物转换为QThread并从那里进行管理。

0 个答案:

没有答案