def join(self, processEvents=True): """ Wait until the execution finishes. """ while self.poll() is None: QThread.currentThread().msleep(50) if processEvents and QThread.currentThread() is qApp.thread(): qApp.processEvents()
def test_task(self): results = [] task = Task(function=QThread.currentThread) task.resultReady.connect(results.append) task.start() self.app.processEvents() self.assertSequenceEqual(results, [QThread.currentThread()]) results = [] thread = QThread() thread.start() task = Task(function=QThread.currentThread) task.moveToThread(thread) self.assertIsNot(task.thread(), QThread.currentThread()) self.assertIs(task.thread(), thread) task.resultReady.connect(results.append, Qt.DirectConnection) task.start() f = task.future() self.assertIsNot(f.result(3), QThread.currentThread()) self.assertIs(f.result(3), results[-1])
def execute(self): """ Never call directly, use `__call__` or `apply_async` instead """ assert(self.thread() is QThread.currentThread()) if self._cancelRequested: self._cancelled = True self._status = 2 self.emit(SIGNAL("finished(QString)"), QString("Cancelled")) return self._started = True self.emit(SIGNAL("starting()")) try: self.result = self.func(*self._args, **self._kwargs) except Exception, ex: print >> sys.stderr, "Exception in thread ", \ QThread.currentThread(), " while calling ", self.func self.emit(SIGNAL("finished(QString)"), QString(repr(ex))) self.emit(SIGNAL("finished(PyQt_PyObject, QString)"), self, QString(repr(ex))) self.emit(SIGNAL("unhandledException(PyQt_PyObject)"), sys.exc_info()) self._exc_info = sys.exc_info() self._status = 1 return
def test_methodinvoke(self): executor = ThreadExecutor() state = [None, None] class StateSetter(QObject): @Slot(object) def set_state(self, value): state[0] = value state[1] = QThread.currentThread() def func(callback): callback(QThread.currentThread()) obj = StateSetter() f1 = executor.submit(func, methodinvoke(obj, "set_state", (object, ))) f1.result() # So invoked method can be called QCoreApplication.processEvents() self.assertIs(state[1], QThread.currentThread(), "set_state was called from the wrong thread") self.assertIsNot(state[0], QThread.currentThread(), "set_state was invoked in the main thread") executor.shutdown(wait=True)
def test_methodinvoke(self): executor = ThreadExecutor() state = [None, None] class StateSetter(QObject): @Slot(object) def set_state(self, value): state[0] = value state[1] = QThread.currentThread() def func(callback): callback(QThread.currentThread()) obj = StateSetter() f1 = executor.submit(func, methodinvoke(obj, "set_state", (object,))) f1.result() # So invoked method can be called QCoreApplication.processEvents() self.assertIs(state[1], QThread.currentThread(), "set_state was called from the wrong thread") self.assertIsNot(state[0], QThread.currentThread(), "set_state was invoked in the main thread") executor.shutdown(wait=True)
def stop(self): print "stopping" print QThread.currentThread() print self.thread() print self.timer.thread() print "Timer thread has changed: %s" % (self.thread_of_timer is self.timer.thread()) self.timer.stop()
def execute(self): """ Never call directly, use `__call__` or `apply_async` instead """ assert (self.thread() is QThread.currentThread()) if self._cancelRequested: self._cancelled = True self._status = 2 self.emit(SIGNAL("finished(QString)"), QString("Cancelled")) return self._started = True self.emit(SIGNAL("starting()")) try: self.result = self.func(*self._args, **self._kwargs) except Exception, ex: print >> sys.stderr, "Exception in thread ", \ QThread.currentThread(), " while calling ", self.func self.emit(SIGNAL("finished(QString)"), QString(repr(ex))) self.emit(SIGNAL("finished(PyQt_PyObject, QString)"), self, QString(repr(ex))) self.emit(SIGNAL("unhandledException(PyQt_PyObject)"), sys.exc_info()) self._exc_info = sys.exc_info() self._status = 1 return
def start(self): print 'Starting watcher' self.abbyy_app = pywinauto.Application().connect(process=self.pid) """@type : Application""" self.abbyy_dialog = self.abbyy_app.window_(class_name='#32770') print QThread.currentThread() self.polling_timer = QTimer() self.polling_timer.setInterval(500) self.polling_timer.timeout.connect(self.poll) self.polling_timer.start()
def _load_data(self, mappings, channel): dtable = HmmDataTable() # XXX read region names from hdf not from settings chreg = "%s__%s" % (channel, self.ecopts.regionnames[channel]) progress = ProgressMsg(max=len(self.files)) for file_ in self.files: position = splitext(basename(file_))[0] progress.meta = meta = ("loading plate: %s, file: %s" % (self.plate, file_)) progress.increment_progress() QThread.currentThread().interruption_point() self.parent().progressUpdate.emit(progress) QtCore.QCoreApplication.processEvents() try: ch5 = cellh5.CH5File(file_, "r", cached=True) for pos in ch5.iter_positions(): # only segmentation if not pos.has_classification(chreg): continue # make dtable aware of all positions, sometime they contain # no tracks and I don't want to ignore them dtable.add_position(position, mappings[position]) if not pos.has_events(): continue objidx = np.array( \ pos.get_events(not self.ecopts.ignore_tracking_branches), dtype=int) tracks = pos.get_class_label(objidx, chreg) try: probs = pos.get_prediction_probabilities(objidx, chreg) except KeyError as e: probs = None grp_coord = cellh5.CH5GroupCoordinate( \ chreg, pos.pos, pos.well, pos.plate) dtable.add_tracks(tracks, position, mappings[position], objidx, grp_coord, probs) finally: ch5.close() if dtable.is_empty(): raise RuntimeError( "No data found for plate '%s' and channel '%s' " % (self.plate, channel)) return dtable, self._load_classdef(chreg)
def setBioMartDatasets(self, datasets): assert(QThread.currentThread() is self.thread()) self.setEnabled(True) self.datasets = [data for data in datasets if getattr(data, "visible", "0") != "0"] self.datasetsCombo.clear() self.datasetsCombo.addItems([data.displayName for data in self.datasets])
def __onRunFinished(self): assert QThread.currentThread() is self.thread() assert self.__state == State.Processing assert self.__pendingTask is not None assert self.sender() is self.__pendingTask.watcher assert self.__pendingTask.future.done() task = self.__pendingTask self.__pendingTask = None try: image_meta = task.future.result() except Exception as err: sys.excepthook(*sys.exc_info()) state = State.Error image_meta = [] self.error(traceback.format_exc()) else: state = State.Done self.error() categories = {} for imeta in image_meta: # derive categories from the path relative to the starting dir dirname = os.path.dirname(imeta.path) relpath = os.path.relpath(dirname, task.startdir) categories[dirname] = relpath self._imageMeta = image_meta self._imageCategories = categories self.__setRuntimeState(state) self.commit()
def setBioMartConfiguration(self, configuration): assert QThread.currentThread() is self.thread() self.setEnabled(True) # parse the xml in the main thread (a long time ago this step was # done in a thread but would frequently cause `expat` to segfault. doc = biomart.parseXML(io.BytesIO(configuration)) config = list(doc.elements("DatasetConfig"))[0] configuration = biomart.DatasetConfig(self.registry, config.tag, config.attributes, config.children) self.clearConfiguration() self.configuration = configuration def hidden(tree): return getattr(tree, "hidden", "false") != "false" or getattr(tree, "hideDisplay", "false") != "false" self.attributePagesTabWidget = tabs = gui.tabWidget(self.attributesConfigurationBox) for page in configuration.elements("AttributePage"): if not hidden(page): page_widget = PageWidget(page, self.dataset, self) gui.createTabPage(tabs, getattr(page, "displayName", ""), widgetToAdd=page_widget, canScroll=True) if self.SHOW_FILTERS: self.filterPagesTabWidget = tabs = gui.tabWidget(self.filtersConfigurationBox) for page in configuration.elements("FilterPage"): if not hidden(page): page_widget = PageWidget(page, self.dataset, self) gui.createTabPage(tabs, getattr(page, "displayName", ""), widgetToAdd=page_widget, canScroll=True) self.afterInit() self.commitButton.setEnabled(True)
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert isinstance(self.task.thread(), _TaskDepotThread) QMetaObject.invokeMethod(self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread())) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. # TODO: If the task encounters an critical error it might not emit # these signals and this Runnable will never complete. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def _fetch_indicators(self, progress=lambda val: None): """Background task for fetching indicators.""" progress(0) def row_item(display_value, item_values=None): """Generate a cell item for a given row.""" if not item_values: item_values = {} item = QtGui.QStandardItem() item.setData(display_value, Qt.DisplayRole) for role, value in item_values.items(): item.setData(value, role) return item progress(10) filter_ = self._main_widget.basic_indicator_filter() data = self._api.get_indicators(filter_=filter_) self._indicator_data = {ind["id"]: ind for ind in data} progress(70) indicators = [[""] + row for row in self._api.get_indicator_list(filter_=filter_)] model = QtGui.QStandardItemModel() model.setHorizontalHeaderLabels(indicators[0]) for row in indicators[1:]: search_string = " | ".join(row).lower() row_data = [row_item(item) for item in row] row_data[0].setData(search_string, TEXTFILTERROLE) row_data[1].setData(self._get_link(row[1]), gui.LinkRole) model.appendRow(row_data) progress(100) if QThread.currentThread() is not QCoreApplication.instance().thread(): model.moveToThread(QCoreApplication.instance().thread()) return model
def __init__( self, files, needPrj ): QThread.__init__( self, QThread.currentThread() ) self.inFiles = files self.needPrj = needPrj self.mutex = QMutex() self.stopMe = 0
def f2(): future = ac.start(em2.g, lambda x: x, QThread.currentThread()) # The doneSignal won't be processed without an event loop. A # thread pool doesn't create one, so make our own to run ``g``. qe = QEventLoop() future._signalInvoker.doneSignal.connect(qe.exit) qe.exec_()
def __init__(self, files, needPrj): QThread.__init__(self, QThread.currentThread()) self.inFiles = files self.needPrj = needPrj self.mutex = QMutex() self.stopMe = 0
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert isinstance(self.task.thread(), _TaskDepotThread) QMetaObject.invokeMethod( self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread()) ) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. # TODO: If the task encounters an critical error it might not emit # these signals and this Runnable will never complete. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert self.task.thread() is _TaskDepotThread.instance() QMetaObject.invokeMethod( self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread()) ) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def setBioMartRegistry(self, registry): assert QThread.currentThread() is self.thread() self.setEnabled(True) self.registry = registry self.marts = [mart for mart in self.registry.marts() if getattr(mart, "visible", "0") != "0"] for mart in self.marts: self.martsCombo.addItem(mart.displayName)
def test_5(self): for _ in self.poolAndThread: with AsyncController(_) as ac: def f(currentThread): self.assertNotEquals(currentThread, QThread.currentThread()) em = Emitter() with WaitForSignal(em.bing, 1000): ac.start(em.g, f, QThread.currentThread())
def foo(a, b): print('Foo ' + str(a) + str(b) + ' in thread ' + str(QThread.currentThread())) if a == 3: # As a test, raise an exception. See if a useful traceback is # printed. asdf time.sleep(0.3) return a + 0.1
def __init__(self, layers, isFiles): QThread.__init__(self, QThread.currentThread()) self.layers = layers self.isFiles = isFiles self.mutex = QMutex() self.stopMe = 0 self.errors = []
def excepthook(exctype, excvalue, exctb): """Called when a Python exception goes unhandled.""" from traceback import format_exception sys.stderr.write(''.join(format_exception(exctype, excvalue, exctb))) if exctype != KeyboardInterrupt: # show dialog, but not when in non-GUI thread if QThread.currentThread() == qApp.thread(): import exception exception.ExceptionDialog(exctype, excvalue, exctb)
def transfer(self, obj, thread): """ Transfer `obj` (:class:`QObject`) instance from this thread to the target `thread` (a :class:`QThread`). """ assert obj.thread() is self assert QThread.currentThread() is self obj.moveToThread(thread)
def setBioMartRegistry(self, registry): assert(QThread.currentThread() is self.thread()) self.setEnabled(True) self.registry = registry self.marts = [mart for mart in self.registry.marts() if getattr(mart, "visible", "0") != "0"] for mart in self.marts: self.martsCombo.addItem(mart.displayName)
def __init__( self, layers, isFiles ): QThread.__init__( self, QThread.currentThread() ) self.layers = layers self.isFiles = isFiles self.mutex = QMutex() self.stopMe = 0 self.errors = []
def _invoke(self): if self._requestCancel: # Skip canceled callables. self._state = self.STATE_CANCELED else: # Run the function, catching any exceptions. self._state = self.STATE_RUNNING QThread.currentThread().setPriority(self._futurePriority) try: self._result = self._f(*self._args, **self._kwargs) except: # Save not just the exception, but also the traceback to provide # better debugging info when this is re-raised in the calling # thread. self._exc_info = sys.exc_info() # Report the results. self._state = self.STATE_FINISHED self._signalInvoker.doneSignal.emit(self)
def is_main_thread(self): """ Indicates whether the caller is on the main gui thread. Returns ------- result : bool True if called from the main gui thread. False otherwise. """ return QThread.currentThread() == self._qapp.thread()
def _stateChanged(self, future, state): """ The `future` state has changed (called by :class:`Future`). """ ev = StateChangedEvent(state) if self.thread() is QThread.currentThread(): QCoreApplication.sendEvent(self, ev) else: QCoreApplication.postEvent(self, ev)
def __init__(self, dir, shapes, inputEncoding, outputFileName, outputEncoding): QThread.__init__(self, QThread.currentThread()) self.baseDir = dir self.shapes = shapes self.inputEncoding = inputEncoding self.outputFileName = outputFileName self.outputEncoding = outputEncoding self.mutex = QMutex() self.stopMe = 0
def run(self): self.eventLoop = QEventLoop() self.eventLoop.processEvents() QObject.connect(self._call, SIGNAL("finished(QString)"), lambda str: self.eventLoop.quit()) QMetaObject.invokeMethod( self._call, "moveToAndInit", Qt.QueuedConnection, Q_ARG("PyQt_PyObject", QThread.currentThread())) self.eventLoop.processEvents() self.eventLoop.exec_()
def _initializemodel(self): assert self.thread() is QThread.currentThread() model, self.gds_info, self.gds = self._inittask.result() model.setParent(self) proxy = self.treeWidget.model() proxy.setFilterKeyColumn(0) proxy.setFilterRole(TextFilterRole) proxy.setFilterCaseSensitivity(False) proxy.setFilterFixedString(self.filterString) proxy.setSourceModel(model) proxy.sort(0, Qt.DescendingOrder) self.progressBarFinished() self.setBlocking(False) self.setEnabled(True) filter_items = " ".join( gds[key] for gds in self.gds for key in self.searchKeys ) tr_chars = ",.:;!?(){}[]_-+\\|/%#@$^&*<>~`" tr_table = str.maketrans(tr_chars, " " * len(tr_chars)) filter_items = filter_items.translate(tr_table) filter_items = sorted(set(filter_items.split(" "))) filter_items = [item for item in filter_items if len(item) > 3] self.completer.model().setStringList(filter_items) # self.filterLineEdit.setItems(filter_items) if self.currentGds: current_id = self.currentGds["dataset_id"] gdss = [(i, qunpack(proxy.data(proxy.index(i, 1), Qt.DisplayRole))) for i in range(proxy.rowCount())] current = [i for i, data in gdss if data and data == current_id] if current: current_index = proxy.index(current[0], 0) self.treeWidget.selectionModel().select( current_index, QItemSelectionModel.Select | QItemSelectionModel.Rows ) self.treeWidget.scrollTo( current_index, QTreeView.PositionAtCenter) for i in range(8): self.treeWidget.resizeColumnToContents(i) self.treeWidget.setColumnWidth( 1, min(self.treeWidget.columnWidth(1), 300)) self.treeWidget.setColumnWidth( 2, min(self.treeWidget.columnWidth(2), 200)) self.updateInfo()
def __init__(self, layer, splitField, encoding, outDir): QThread.__init__(self, QThread.currentThread()) self.layer = layer self.field = splitField self.encoding = encoding self.outDir = outDir self.mutex = QMutex() self.stopMe = 0 self.errors = []
def __call__(self, exc_type, exc_value, tb): if self._stream: header = exc_type.__name__ + ' Exception' if QThread.currentThread() != QCoreApplication.instance().thread(): header += " (in non-GUI thread)" text = traceback.format_exception(exc_type, exc_value, tb) text.insert(0, '{:-^79}\n'.format(' ' + header + ' ')) text.append('-' * 79 + '\n') self._stream.writelines(text) self.handledException.emit(((exc_type, exc_value, tb), self._canvas))
def __init__( self, inPoly, inPoints, fieldName, outPath, encoding ): QThread.__init__( self, QThread.currentThread() ) self.mutex = QMutex() self.stopMe = 0 self.interrupted = False self.layerPoly = inPoly self.layerPoints = inPoints self.fieldName = fieldName self.outPath = outPath self.encoding = encoding
def write(self, str): """ Emulate write function """ if self.guistream.thread() != QThread.currentThread(): sys_stdout.write(str) e = QEvent(QEvent.Type(RedirectionEventId)) e.txt = str QApplication.postEvent(self.guistream, e) pass else: self.guistream.write(str)
def write(self, str): """ Emulate write function """ if self.guistream.thread() != QThread.currentThread(): sys_stdout.write(str) e = QEvent(QEvent.Type(RedirectionEventId)) e.txt = str QApplication.postEvent(self.guistream,e) pass else: self.guistream.write(str)
def run(self): self.eventLoop = QEventLoop() self.eventLoop.processEvents() QObject.connect(self._call, SIGNAL("finished(QString)"), lambda str: self.eventLoop.quit()) QMetaObject.invokeMethod(self._call, "moveToAndInit", Qt.QueuedConnection, Q_ARG("PyQt_PyObject", QThread.currentThread())) self.eventLoop.processEvents() self.eventLoop.exec_()
def __init__(self): super(Stopper, self).__init__() print "current thread 2 %r" % QThread.currentThread() self.timer = QTimer() self.thread_of_timer = self.timer.thread() print "stopper.timer thread: %r" % self.thread_of_timer self.timer.setInterval(1000) self.timer.timeout.connect(self.prnt_msg) self.start_timer.connect(self.start) self.stop_timer.connect(self.stop)
def test_executor(self): executor = ThreadExecutor() f = executor.submit(QThread.currentThread) self.assertIsNot(f.result(3), QThread.currentThread()) f = executor.submit(lambda: 1 / 0) with self.assertRaises(ZeroDivisionError): f.result() results = [] task = Task(function=QThread.currentThread) task.resultReady.connect(results.append, Qt.DirectConnection) f = executor.submit(task) self.assertIsNot(f.result(3), QThread.currentThread()) executor.shutdown()
def onResultsReady(self, results): """Handle the results of centering and z-scoring """ assert(QThread.currentThread() is self.thread()) Gc, Rc, z_scores = results self.setEnabled(True) self.progressBarFinished() self.centered = Gc, Rc self.z_scores = z_scores self.plotMA(Gc, Rc, z_scores, self.zCutoff) self.commit()
def __init__(self, function, inputLayer, useSelection, tolerance, writeShape, shapePath, shapeEncoding): QThread.__init__(self, QThread.currentThread()) self.inputLayer = inputLayer self.useSelection = useSelection self.tolerance = tolerance self.writeShape = writeShape self.outputFileName = shapePath self.outputEncoding = shapeEncoding self.myFunction = function self.mutex = QMutex() self.stopMe = 0