Skip to content

Instantly share code, notes, and snippets.

@anqxyr
Last active July 5, 2018 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anqxyr/1802849fb2b9addc1ccead0e30a648c7 to your computer and use it in GitHub Desktop.
Save anqxyr/1802849fb2b9addc1ccead0e30a648c7 to your computer and use it in GitHub Desktop.
PyQt lazy threading
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