Last active
July 5, 2018 14:59
-
-
Save anqxyr/1802849fb2b9addc1ccead0e30a648c7 to your computer and use it in GitHub Desktop.
PyQt lazy threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WORKERS = [] | |
class BackgroundWorker(QtCore.QThread): | |
result = QtCore.pyqtSignal(object) | |
exception = QtCore.pyqtSignal(object) | |
def __init__(self, func, fin): | |
super().__init__() | |
WORKERS.append(self) | |
self.finished.connect(lambda: WORKERS.remove(self)) | |
self.func = func | |
if fin: | |
self.result.connect(lambda x: fin(x)) | |
self.exception.connect(self.raise_exception) | |
def run(self): | |
try: | |
result = self.func() | |
except Exception as e: | |
self.exception.emit(e) | |
else: | |
self.result.emit(result) | |
def raise_exception(self, e): | |
"""Raise exception in the main thread.""" | |
raise e | |
def run_daemon(func, *args, fin=None, **kwargs): | |
noargs = lambda: func(*args, **kwargs) | |
BackgroundWorker(noargs, fin).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment