def piteca_excepthook(exctype, value, tb): """ A method to catch all unhandled exception during PITECA's run . :param exctype: the type of exception :param value: the message of the exception (use str(value)) :param tb: traceback """ # if not gb.should_exit_on_error: # # If we are on main thread but don't want to close PITECA # dialog_utils.print_error(constants.UNEXPECTED_EXCEPTION_MSG[:-1] + ": " + str(value)) # return # Show user the full error value only if it is a PITECA error if exctype == definitions.PitecaError: msg = str(value.message) else: msg = constants.UNEXPECTED_EXCEPTION_MSG if int(QThread.currentThreadId()) == main_thread_id: definitions.print_in_debug(value) traceback.print_tb(tb) dialog_utils.print_error(msg + ". PITECA will be now closed") sys.exit() else: # The exception_occurred_sig should be defined in every thread class in PITECA definitions.print_in_debug(value) definitions.print_in_debug(exctype) traceback.print_tb(tb) QThread.currentThread().exception_occurred_sig.emit(msg)
def __init__(self, args): super().__init__() self.args = args self.setWindowTitle("VPilot Drive GUI") form_layout = QVBoxLayout() self.setLayout(form_layout) self.resize(400, 800) self.button_start = QPushButton() self.button_start.clicked.connect(self.start_thread) self.button_start.setText("Start") form_layout.addWidget(self.button_start) self.button_stop = QPushButton() self.button_stop.clicked.connect(self.abort_worker) self.button_stop.setText("Stop") self.button_stop.setDisabled(True) form_layout.addWidget(self.button_stop) # self.log = QTextEdit() # form_layout.addWidget(self.log) self.label = QLabel(self) # self.label.setGeometry(QRect(20, 20, 320, 160)) self.label.resize(320, 160) # self.progress = QTextEdit() # form_layout.addWidget(self.progress) QThread.currentThread().setObjectName( 'main') # threads can be named, useful for log output self.__worker_done = None self.__thread = None
def __init__(self, parent=None): """ class initialization. initializes the Leecher class Parameters ---------- nothing Returns ------- nothing """ super(Leecher, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setup_signals() self.center() self.show() self.find_seeders_alive() self.setup_initial_screen() QThread.currentThread().setObjectName( 'main') # threads can be named, useful for log output self.__workers_done = None self.__threads = [] self.filename_download = '' self.filename = ''
def __init__(self): super(MyWindow, self).__init__() self.setWindowTitle("智能识别") self.resize(800,450) self.txt_print = QTextEdit() self.start_btn = QPushButton() self.stop_btn = QPushButton() self.Camera_label = QLabel() self.wait_label = QLabel() # self.txt_log.setText("点击'开始‘ 开始识别") self.start_btn.setText("开始识别") self.stop_btn.setText("停止识别") self.stop_btn.setDisabled(True) self.Camera_label.setText("未开始") self.wait_label.setText("等待中") self.start_btn.clicked.connect(self.start_workers) self.stop_btn.clicked.connect(self.abort_workers) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(self.start_btn,1,0) grid.addWidget(self.stop_btn,2,0) grid.addWidget(self.txt_print,4,0) grid.addWidget(self.wait_label,3,0) grid.addWidget(self.Camera_label,1,1,4,4) self.setLayout(grid) QThread.currentThread().setObjectName('main') self.__workers_done = None self.__threads = None
def __init__(self, main_window): super().__init__() QThread.currentThread().setObjectName('tab_downloader') loadUi(resource_path('qt_assets/tabs/tab_download.ui'), self) self.main_window = main_window self.init_ui() self.show()
def __init__(self): super(MainWindow, self).__init__() uic.loadUi(qtCreatorFile, self) self.threads = [] mainThreadID = int(QThread.currentThread().currentThreadId()) print("MainThread ID: {}".format(mainThreadID)) QThread.currentThread().setObjectName("Thread_Main") print("MainThread name is: {}".format( QThread.currentThread().objectName())) self.pb1.clicked.connect(self.pb1Action) self.pb1Object = UpdateLogger(2) self.pb1Thread = QThread() self.pb1Thread.setObjectName("Thread_pb1") self.threads.append(self.pb1Thread) self.pb1Object.moveToThread(self.pb1Thread) self.pb1Object.finished.connect(self.updateLogger) self.pb1Object.update.connect(self.updateLogger) self.pb1Thread.started.connect(self.pb1Object.running) self.pb2.clicked.connect(self.pb2Action) self.pb2Object = UpdateLogger(3) self.pb2Thread = QThread() self.pb2Thread.setObjectName("Thread_pb2") self.threads.append(self.pb2Thread) self.pb2Object.moveToThread(self.pb2Thread) print(self.pb2Object.threadName) self.pb2Object.finished.connect(self.updateLogger) self.pb2Object.update.connect(self.updateLogger) self.pb2Thread.started.connect(self.pb2Object.running) for t in self.threads: print(t.objectName()) self.pb3.clicked.connect(self.pb3Action)
def __init__(self): super().__init__() self.setWindowTitle("Thread Example") form_layout = QVBoxLayout() self.setLayout(form_layout) self.resize(400, 800) self.btn_start = QPushButton() self.btn_start.clicked.connect(self.start_workers) self.btn_start.setText("Start {} threads".format(self.NUM_THREADS)) form_layout.addWidget(self.btn_start) self.btn_stop = QPushButton() self.btn_stop.clicked.connect(self.abort_workers) self.btn_stop.setText("Stop threads") self.btn_stop.setDisabled(True) form_layout.addWidget(self.btn_stop) self.txt_log = QTextEdit() form_layout.addWidget(self.txt_log) self.txt_prg = QTextEdit() form_layout.addWidget(self.txt_prg) # 主线程名 QThread.currentThread().setObjectName('main') self.__workers_done = None self.__threads = None
def __init__(self): super().__init__() self.setWindowTitle("Thread Example") form_layout = QVBoxLayout() self.setLayout(form_layout) self.resize(400, 800) self.button_start_threads = QPushButton() self.button_start_threads.clicked.connect(self.start_threads) self.button_start_threads.setText("Start {} threads".format(self.NUM_THREADS)) form_layout.addWidget(self.button_start_threads) self.button_stop_threads = QPushButton() self.button_stop_threads.clicked.connect(self.abort_workers) self.button_stop_threads.setText("Stop threads") self.button_stop_threads.setDisabled(True) form_layout.addWidget(self.button_stop_threads) self.log = QTextEdit() form_layout.addWidget(self.log) self.progress = QTextEdit() form_layout.addWidget(self.progress) QThread.currentThread().setObjectName('main') # threads can be named, useful for log output self.__workers_done = None self.__threads = None
def __init__(self): super().__init__() self.setWindowTitle("Dummy Files Creator") self.setWindowIcon(QtGui.QIcon(':/icon.png')) QThread.currentThread().setObjectName('main') self.__threads = [] self._files_created = [] self._create_ui()
def __init__(self): super().__init__() self.keyboard() QThread.currentThread().setObjectName('main') self.__work_done=None self.__threads=None self.animation=None self.animation = None
def update_prices(self): if self.stop_exec: self.timer.stop() QThread.currentThread().quit() return for item in self.lookup_list: insn, rn, azn = item.split(':') try: s = boto3.Session(profile_name=self.profile, region_name=rn) ec2 = s.client('ec2') response = ec2.describe_spot_price_history( AvailabilityZone=azn, InstanceTypes=[insn], ProductDescriptions=["Linux/UNIX"], StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=5), EndTime=datetime.datetime.utcnow()) if response and 'SpotPriceHistory' in response: if len(response['SpotPriceHistory']) >= 1: if 'SpotPrice' in response['SpotPriceHistory'][0]: self.prices[item] = float( response['SpotPriceHistory'][0]['SpotPrice']) self.lookup_list.remove(item) self.sig_update_price.emit(item, self.prices[item]) else: print("Price request response invalid for {} nop". format(item)) self.sig_update_price.emit(item, 0.00) self.lookup_list.remove(item) else: print("Price request response invalid for {} (len)". format(item)) self.sig_update_price.emit(item, 0.00) self.lookup_list.remove(item) else: print("Price request response invalid for {}".format(item)) self.sig_update_price.emit(item, 0.00) self.lookup_list.remove(item) except ClientError as e: print(e) self.sig_error.emit(str(e)) pass except gaierror as e: print(e) self.sig_error.emit(str(e)) pass except NewConnectionError as e: print(e) self.sig_error.emit(str(e)) pass except EndpointConnectionError as e: print(e) self.sig_error.emit(str(e)) pass
def __init__(self, parent=None): super(MainGui, self).__init__(parent) self.setupUi(self) self.initial_ui() # Make any cross object connections. self._connectSignals() QThread.currentThread().setObjectName( 'main') # threads can be named, useful for log output self.__threads = None
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 _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 get_hoster_links(self) -> None: try: req = self.scraper.get(self.link_url) bs = BeautifulSoup(req.text, 'lxml') links = bs.select('div.post h2[style="text-align: center;"]') self.setHosters.emit(links) except HTTPError: print(sys.exc_info()[0]) # noinspection PyTypeChecker QMessageBox.critical(None, 'ERROR NOTIFICATION', sys.exc_info()[0]) QThread.currentThread().quit() except IndexError: self.noLinks.emit() QThread.currentThread().quit()
def detect_video(widget=None, with_tracking=None): if not widget: args = arg_parse() else: args = widget.args # Check files if args.video != 0: if not os.path.exists(args.video): print_info(widget, True, "error", "No file with the name {}".format(args.video)) mimetypes.init() mime_start = mimetypes.guess_type(args.video)[0] if mime_start: mime_start = mime_start.split('/')[0] if mime_start != 'video': print_info(widget, True, "error", "No video file with the name {}".format(args.video)) # Set up the neural network # Detection phase video_file = args.video # or path to the video file. if type(video_file) == int: # for webcam reading_thread = ReadFramesThread(0, args, with_tracking, widget).start() else: reading_thread = ReadFramesThread(video_file, args, with_tracking, widget).start() while reading_thread.has_images() or (not reading_thread.stopped): if widget.obj.cancel: reading_thread.cancel() widget.obj.cancel = False QThread.currentThread().quit() return if widget.obj.pause: reading_thread.pause() widget.obj.pauseMutex.lock() widget.obj.pauseCond.wait(widget.obj.pauseMutex) widget.obj.pauseMutex.unlock() image_handler = reading_thread.get_image() last_contour = image_handler.get_last_contour() if last_contour: print_info(widget, False, "contour_ready", last_contour) print_info(widget, False, "image_ready", image_handler) key = cv2.waitKey(1) if key & 0xFF == ord('q'): break
def on_timeout(self): if self.stop_exec: self.timer.stop() QThread.currentThread().quit() if self.do_update: self.do_update = False self.items.clear() try: s = boto3.Session(profile_name=self.profile, region_name=self.region) s3 = s.client('s3') response = s3.list_objects(Bucket='cloudian-qtspots', Prefix=self.prefix) if 'Contents' in response: for o in response['Contents']: if self.rfilter != '': if pathlib.PurePosixPath(o['Key']).name.endswith( self.rfilter): self.items.append(o['Key'].replace( self.prefix, '')) self.sig_progress.emit("Loaded {}".format( pathlib.PurePosixPath(o['Key']).name)) else: self.items.append(o['Key'].replace( self.prefix, '')) self.sig_progress.emit("Loaded {}".format( pathlib.PurePosixPath(o['Key']).name)) self.sig_update_finished.emit(self.items) if len(self.items) == 0: self.sig_update_error.emit( "Loader returned an empty result.") except ClientError as e: print(e) self.sig_update_error.emit(str(e)) pass except gaierror as e: print(e) self.sig_update_error.emit(str(e)) pass except NewConnectionError as e: print(e) self.sig_update_error.emit(str(e)) pass except EndpointConnectionError as e: print(e) self.sig_update_error.emit(str(e)) pass
def _run_blocking_event_loop(self, timeout: float = None) -> None: """Start the main event loop for this :py:class:`ImageDisplay`. """ LOG.info("Running Qt Main Event Loop.") # Run the Qt main event loop to update the display and # process timeout and/or key events. if self.event_loop_is_running(): raise RuntimeError("Only one background thread is allowed.") self._event_loop = QThread.currentThread() if timeout is not None: milliseconds = int(timeout * 1000) timer = QTimer() timer.setInterval(milliseconds) timer.setSingleShot(True) timer.timeout.connect(self._view.onTimer) timer.start() LOG.debug("Starting Qt Main Event Loop (exec_)") self._application.exec_() LOG.debug("Qt Main Event Loop (exec_) has ended.") if timeout is not None: timer.stop() timer.timeout.disconnect(self._view.onTimer) self._event_loop = None LOG.info("Qt Main Event Loop finished (event loop=%s, closed=%s).", self.event_loop_is_running(), self.closed)
def work(self): """ Pretend this worker method does work that takes a long time. During this time, the thread's event loop is blocked, except if the application's processEvents() is called: this gives every thread (incl. main) a chance to process events, which in this sample means processing signals received from GUI (such as abort). """ thread_name = QThread.currentThread().objectName() thread_id = int( QThread.currentThreadId()) # cast to int() is necessary self.sig_msg.emit('Running worker #{} from thread "{}" (#{})'.format( self.__id, thread_name, thread_id)) for step in range(100): time.sleep(0.1) self.sig_step.emit(self.__id, 'step ' + str(step)) # check if we need to abort the loop; need to process events to receive signals; # app.processEvents() # this could cause change to self.__abort if self.__abort: # note that "step" value will not necessarily be same for every thread self.sig_msg.emit('Worker #{} aborting work at step {}'.format( self.__id, step)) break self.sig_done.emit(self.__id)
def echo(self, message): """Cheap debug tool """ now = Datetime.utcnow() messageBar = self.iface.messageBar() threadName = QThread.currentThread().objectName() messageBar.pushMessage(threadName, "[%s] %s" % (now, message))
def _task_finished(self, f): """ Parameters ---------- f : Future The future instance holding the result of learner evaluation. """ assert self.thread() is QThread.currentThread() assert self._task is not None assert self._task.future is f assert f.done() self._task = None self.progressBarFinished() try: results = f.result() # type: dict self.on_finish(results) except Exception as ex: # Log the exception with a traceback log = logging.getLogger() log.exception(__name__, exc_info=True) self.error("Exception occurred during evaluation: {!r}".format(ex))
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 begin(self): for page in range(self.maxpages): if QThread.currentThread().isInterruptionRequested(): return self.scrape(page) self.complete = True self.workFinished.emit()
def helperForObservable(self, observable: Observable, interests=None, notify: Callable = None, create: bool = False, remove: bool = False) -> Observable.Observer: if self._qObserverHelpers is None: raise RuntimeError("It seems QObserver's constructor was not " "called (QObserverHelpers is not set)") key = type(observable).Change if key not in self._qObserverHelpers: if not create: raise RuntimeError("No QObserverHelper for observing " f"{type(observable)} in {self}") helper = QObserver.QObserverHelper(self, observable, interests, notify) # make sure that event processing for the helper object # is done in th main thread: mainThread = QApplication.instance().thread() if mainThread != QThread.currentThread(): LOG.warning("Moving observer helper for %s to main Thread", observable) helper.moveToThread(mainThread) self._qObserverHelpers[key] = helper elif remove: return self._qObserverHelpers.pop(key) return self._qObserverHelpers[key]
def observe(self, observable: Observable, interests: Observable.Change = None, notify: Callable = None) -> None: """Observe an :py:class:`Observable`. Note: The type of the observable (currently) has to be suitable for this class, i.e. it is not necessary to declare it with `qobservables` arguments at class definition, but that may change in future. Arguments --------- observable: Observable The object to observer. interests: Notification we are interested in. notify: Callable The method to invoke on notification. If none is provided, the default notifiaction method of the observable is used. Raises ------ TypeError: The observable is of inapropriate type. """ if not isinstance(observable, Observable): raise TypeError(f"{type(self).__name__} is trying to observe " f"a non-observable ({type(observable)})") mainThread = QApplication.instance().thread() currentThread = QThread.currentThread() qObserverHelper = \ self.helperForObservable(observable, create=True, interests=interests, notify=notify) qObserverHelper.startObservation(interests=interests, notify=notify)
def _analyze(self, cellanalyzer): thread = QThread.currentThread() imax = sum([len(n) for n in self.sample_positions.values()]) thread.statusUpdate(min=0, max=imax) stopwatch = StopWatch(start=True) crd = Coordinate(self.plate_id, self.position, self._frames, list(set(self.ch_mapping.values()))) for frame, channels in self._imagecontainer( \ crd, interrupt_channel=True, interrupt_zslice=True): thread.interruption_point() txt = '%s, %s, T %d, (%d/%d)' \ %(self.plate_id, self.position, frame, self._frames.index(frame)+1, len(self._frames)) thread.statusUpdate(meta="Classifier training: ", text=txt, interval=stopwatch.interim(), increment=True) stopwatch.reset(start=True) # initTimepoint clears channel_registry cellanalyzer.initTimepoint(frame) self.register_channels(cellanalyzer, channels) cellanalyzer.collectObjects(self.plate_id, self.position, self.sample_readers, self.learner)
def panel(self, panel_id: str, create: bool = False, show: bool = False) -> Panel: """Get the panel for a given panel identifier. Optionally create that panel if it does not yet exist. Arguments --------- panel_id: The panel identifier. This must be one of the identifiers from the _panelMetas list. create: A flag indicating if the panel should be created in case it does not exist yet. show: A flag indicatin if the panel should be shown, i.e., made the current panel. Raises ------ KeyError: The given panel identifier is not known. ValueError: The panel requested has not yet been created and no creation was requested. """ if not any(m.id == panel_id for m in self._panelMetas): raise KeyError(f"There is no panel with id '{panel_id}' " "in DeepVisMainWindow.") if QThread.currentThread() != self.thread(): # method was called from different thread # emit signal to run in main thread self.panel_signal.emit(panel_id, create, show) return meta = self._panelMeta(panel_id) panel = None if create: index = 0 label = self._tabs.tabText(index) for m in self._panelMetas: if label == meta.label: panel = self._tabs.widget(index) break if m.id == meta.id: self._newPanel(meta, index, m.label, show) # FIXME[hack]: panel creation is asynchronous and # hence does not really fit in this synchronous # function! API should be changed accordingly! panel = None break if label == m.label: index += 1 label = self._tabs.tabText(index) else: index = self._panelTabIndex(panel_id) panel = self._tabs.widget(index) if show and panel is not None: self._tabs.setCurrentIndex(index) return panel
def call_in_gui_thread(function, *args, **kw): application = Application.instance if QThread.currentThread() is Application.gui_thread: return function(*args, **kw) else: application.postEvent(application, CallFunctionEvent(function, args, kw))
def progress_check(self, stream = None, chunk = None, bytes_remaining = None): # Gets the percentage of the file that has been downloaded. # print(stream, file_size) file_size = stream.filesize percent = (100*(file_size-bytes_remaining))/file_size now_thread = QThread.currentThread() now_thread.set_value.emit(percent)
def direct(self, flows): flownum = 0 child_types = [] for flownum, flow in enumerate(flows, start=1): self.raw_line.emit("Flow {0}: {1} -> {2}".format( flownum, flow.source, flow.target)) for rule in sorted(flow.rules): self.raw_line.emit(" {0}".format(rule)) self.raw_line.emit("") # Generate results for flow browser if self.out: child_types.append( (flow.target, sorted(str(r) for r in flow.rules))) else: child_types.append( (flow.source, sorted(str(r) for r in flow.rules))) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} information flow(s) found.\n".format(flownum)) self.log.info("{0} information flow(s) found.".format(flownum)) # Update browser: root_type = self.query.source if self.out else self.query.target self.flows.emit(str(root_type), self.out, sorted(child_types))
def direct(self, transitions): i = 0 child_types = [] for i, step in enumerate(transitions, start=1): self.raw_line.emit("Transition {0}: {1} -> {2}\n".format(i, step.source, step.target)) sort_transition(step) print_transition(self.raw_line.emit, step) # Generate results for flow browser if self.out: child_types.append((step.target, step)) else: child_types.append((step.source, step)) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} domain transition(s) found.".format(i)) self.log.info("{0} domain transition(s) found.".format(i)) # Update browser: root_type = self.query.source if self.out else self.query.target self.trans.emit(str(root_type), self.out, sorted(child_types))
def run(self): print(QThread.currentThread(), ' is running ...') print(QDir.homePath(), QDir.currentPath()) rootdir = QDir.homePath() + '/pics' list = os.listdir(rootdir) #列出文件夹下所有的目录与文件 for i in range(0, min(len(list), 200)): path = os.path.join(rootdir, list[i]) types = ('.bmp', '.jpg', '.tif', '.png') if os.path.isfile(path) and path.endswith(types): # self.image_list[path] = QImage(path) self.image_list.append((path, QImage(path))) self.image_list.sort() sorted(self.image_list, key=operator.itemgetter(0)) if len(self.image_list) == 0: return self.bStop = False while self.isRunning(): # break # for (k,v) in self.image_list.items(): # 字典类型遍历 随机访问 会乱序 for k, v in enumerate(self.image_list): # print(k,v) # print(type(k),type(v)) # self.evt_showImg.emit(k,v) self.evt_showImg.emit(v[0], v[1]) ## 发射自定义信号 if (self.isInterruptionRequested()): print("----> get isInterruptionRequested") self.bStop = True break QThread.msleep(25) if self.bStop: break print("----> thread quit here!!")
def direct(self, transitions): i = 0 child_types = [] for i, step in enumerate(transitions, start=1): self.raw_line.emit("Transition {0}: {1} -> {2}\n".format( i, step.source, step.target)) sort_transition(step) print_transition(self.raw_line.emit, step) # Generate results for flow browser if self.out: child_types.append((step.target, step)) else: child_types.append((step.source, step)) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} domain transition(s) found.".format(i)) self.log.info("{0} domain transition(s) found.".format(i)) # Update browser: root_type = self.query.source if self.out else self.query.target self.trans.emit(str(root_type), self.out, sorted(child_types))
def direct(self, flows): flownum = 0 child_types = [] for flownum, flow in enumerate(flows, start=1): self.raw_line.emit("Flow {0}: {1} -> {2}".format(flownum, flow.source, flow.target)) for rule in sorted(flow.rules): self.raw_line.emit(" {0}".format(rule)) self.raw_line.emit("") # Generate results for flow browser if self.out: child_types.append((flow.target, sorted(str(r) for r in flow.rules))) else: child_types.append((flow.source, sorted(str(r) for r in flow.rules))) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} information flow(s) found.\n".format(flownum)) self.log.info("{0} information flow(s) found.".format(flownum)) # Update browser: root_type = self.query.source if self.out else self.query.target self.flows.emit(str(root_type), self.out, sorted(child_types))
def foo(a, b): print('Foo {} {} in thread {}'.format(a, b, 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): print("Worker.init:", QThread.currentThread()) # Delay creation so we are in the correct thread self.dbus_loop = DBusQtMainLoop(set_as_default=False) self.session_bus = dbus.SessionBus(mainloop=self.dbus_loop) self.dbus_thumbnailer = DBusThumbnailer(self.session_bus) self.sig_thing_requested.connect(self.on_thing_requested)
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 test_5(self): for _ in self.poolAndThread: with AsyncController(_) as ac: def f(currentThread): self.assertNotEqual(currentThread, QThread.currentThread()) em = Emitter() with WaitForSignal(em.bing, 1000): ac.start(em.g, f, QThread.currentThread())
def __call__(self): if self.params_ec.position_labels: self._check_mapping_files() progress = ProgressMsg(max=len(self.plates), meta="Error correction...") for i, plate in enumerate(self.plates): QThread.currentThread().interruption_point() progress.text = ("Plate: '%s' (%d / %d)" %(plate, i+1, len(self.plates))) self.progressUpdate.emit(progress) ch5file = join(self._outdirs[plate], 'hdf5', "_all_positions.ch5") runner = PositionRunner(plate, self._outdirs[plate], self.params_ec, parent=self, ch5file=ch5file) runner() self.progressUpdate.emit(progress)
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 _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 function_wrapper(*args, **kw): application = Application.instance if QThread.currentThread() is Application.gui_thread: return function(*args, **kw) else: if wait: executor = FunctionExecutor(function) application.postEvent(application, CallFunctionEvent(executor, args, kw)) return executor.wait() else: application.postEvent(application, CallFunctionEvent(function, args, kw))
def _load_data(self, channel): dtable = HmmDataTable() # XXX read region names from hdf not from settings mask = "%s__%s" %(channel, self.ecopts.regionnames[channel]) c = 2 if self.ecopts.write_gallery: c += 1 thread = QThread.currentThread() with Ch5File(self.ch5file, mode="r") as ch5: layout = ch5.layout(self.plate) mappings = PlateMapping(layout) thread.statusUpdate(min=0, max=ch5.numberSites(self.plate) + c) for site in ch5.iterSites(): ws = "%s_%02d" %(site.well, int(site.site)) thread.statusUpdate( text="loading plate: %s, file: %s" %(site.plate, ws)) thread.increment.emit() thread.interruption_point() QtCore.QCoreApplication.processEvents() if not ch5.hasClassifier(mask): continue # make dtable aware of all positions, sometime they contain # no tracks and I don't want to ignore them dtable.add_position(ws, mappings[ws]) if not ch5.hasEvents(site): continue objidx = ch5.events(site, self.ecopts.ignore_tracking_branches) tracks = np.asarray(ch5.predictions(site, mask))[objidx] try: probs = ch5.probabilities(site, mask)[objidx, :] except KeyError as e: probs = None site.mask = mask dtable.add_tracks(tracks, ws, mappings[ws], objidx, site, probs) if dtable.is_empty(): raise RuntimeError( "No data found for plate '%s' and channel '%s' " %(self.plate, channel)) return dtable, self._load_classdef(mask)
def direct(self, transitions): i = 0 for i, step in enumerate(transitions, start=1): self.raw_line.emit("Transition {0}: {1} -> {2}\n".format(i, step.source, step.target)) self.print_transition(step) if QThread.currentThread().isInterruptionRequested() or (i >= self.query.limit): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} domain transition(s) found.".format(i))
def g(self, future): self.thread = QThread.currentThread() # Always bing, even if there's an exception. try: # Retrieve the result, even if it won't be checked, to make sure # that no exceptions were raised. self.result = future.result if self.expected: self.assertEqual(self.expected, self.result) except: raise finally: self.bing.emit()
def show_message(self, text, error=False): if self.isVisible(): self.queue.append({'error': error, 'message': text}) self._interval = 1.5 return if error: self._set_error_style() else: self._set_normal_style() self.setText(str(len(self.queue)) + ': ' + text) self.show() self.timer.moveToThread(QThread.currentThread()) self.timer.start(self._interval * 1000)
def main(argv): signal.signal(signal.SIGINT, signal.SIG_DFL) app = QCoreApplication(argv) print("Starting:", QThread.currentThread()) fac1 = WorkerFacade("1") fac2 = WorkerFacade("2") for i in range(10): print("Requesting", i) fac1.request_thing("Foo" + str(i), lambda x: print("Got:", x)) fac2.request_thing("Foo" + str(i), lambda x: print("Got:", x)) def quits(): print("calling quits") fac1.on_quit() fac2.on_quit() def app_quit(): print("App quit") quits() app.quit() # Calling QThread.quit() will not terminate the thread until all # signals have been processed # # Or not, calling quits early will cause a segfault when dbus is # involved. The requested quit signal isn't getting processed QTimer.singleShot(2000, quits) # QThread must be all destroyed before the application is # quitting, else ugly "Aborted (core dumped)" will result QTimer.singleShot(1500, app_quit) print("Entering event loop:", QThread.currentThread()) app.exec() print("Cleanly exited")
def direct(self, flows): flownum = 0 for flownum, flow in enumerate(flows, start=1): self.raw_line.emit("Flow {0}: {1} -> {2}".format(flownum, flow.source, flow.target)) for rule in sorted(flow.rules): self.raw_line.emit(" {0}".format(rule)) self.raw_line.emit("") if QThread.currentThread().isInterruptionRequested() or (flownum >= self.query.limit): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} information flow(s) found.\n".format(flownum))
def __call__(self): thread = QThread.currentThread() for i, plate in enumerate(self.plates): thread.interruption_point() ch5file = join(self._outdirs[plate], "%s.ch5" %plate) runner = PositionRunner(plate, self._outdirs[plate], self.params_ec, parent=self, ch5file=ch5file) runner() txt = ("Plate: '%s' (%d / %d)" %(plate, i+1, len(self.plates))) thread.statusUpdate(text=txt)
def transitive(self, paths): i = 0 for i, path in enumerate(paths, start=1): self.raw_line.emit("Domain transition path {0}:".format(i)) for stepnum, step in enumerate(path, start=1): self.raw_line.emit("Step {0}: {1} -> {2}\n".format(stepnum, step.source, step.target)) self.print_transition(step) if QThread.currentThread().isInterruptionRequested() or (i >= self.query.limit): break else: QThread.yieldCurrentThread() self.raw_line.emit("{0} domain transition path(s) found.".format(i))
def test_6(self): # Don't test with one pooled thread -- this test expects at least two # threads. with AsyncController(2) as ac: q = Queue() def f(): q.get() return QThread.currentThread() em1 = Emitter() em2 = Emitter() ac.start(em1.g, f) ac.start(em2.g, f) with WaitForSignal(em1.bing, 1000), WaitForSignal(em2.bing, 1000): q.put(None) q.put(None) s = set([em1.result, em2.result, QThread.currentThread()]) self.assertEqual(len(s), 3)
def read(self): """Blocking read loop which emits got_line when a new line arrived.""" # We open as R/W so we never get EOF and have to reopen the pipe. # See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/ # We also use os.open and os.fdopen rather than built-in open so we can # add O_NONBLOCK. fd = os.open(self._filepath, os.O_RDWR | os.O_NONBLOCK) # pylint: disable=no-member self.fifo = os.fdopen(fd, 'r') while True: log.procs.debug("thread loop") ready_r, _ready_w, _ready_e = select.select([self.fifo], [], [], 1) if ready_r: log.procs.debug("reading data") for line in self.fifo: self.got_line.emit(line.rstrip()) if QThread.currentThread().isInterruptionRequested(): self.finished.emit() return
def run(self): flownum = 0 child_types = [] for flownum, flow in enumerate(self.query.infoflows(self.type_, out=self.out), start=1): # Generate results for flow browser if self.out: child_types.append((flow.target, sorted(str(r) for r in flow.rules))) else: child_types.append((flow.source, sorted(str(r) for r in flow.rules))) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.log.debug("{0} additional information flow(s) found.".format(flownum)) # Update browser: self.flows.emit(sorted(child_types))
def run(self): transnum = 0 child_types = [] for transnum, trans in enumerate(self.query.transitions(self.type_), start=1): # Generate results for browser sort_transition(trans) if self.out: child_types.append((trans.target, trans)) else: child_types.append((trans.source, trans)) if QThread.currentThread().isInterruptionRequested(): break else: QThread.yieldCurrentThread() self.log.debug("{0} additional domain transition(s) found.".format(transnum)) # Update browser: self.trans.emit(sorted(child_types))
def transitive(self, paths): pathnum = 0 for pathnum, path in enumerate(paths, start=1): self.raw_line.emit("Flow {0}:".format(pathnum)) for stepnum, step in enumerate(path, start=1): self.raw_line.emit(" Step {0}: {1} -> {2}".format(stepnum, step.source, step.target)) for rule in sorted(step.rules): self.raw_line.emit(" {0}".format(rule)) self.raw_line.emit("") if QThread.currentThread().isInterruptionRequested() or (pathnum >= self.query.limit): break else: QThread.yieldCurrentThread() self.raw_line.emit("") self.raw_line.emit("{0} information flow path(s) found.\n".format(pathnum))
def update(self): """Run the query and update results.""" self.model.beginResetModel() results = [] counter = 0 for counter, item in enumerate(self.query.results(), start=1): results.append(item) self.raw_line.emit(str(item)) if QThread.currentThread().isInterruptionRequested(): break elif not counter % 10: # yield execution every 10 rules QThread.yieldCurrentThread() self.model.resultlist = results self.model.endResetModel() self.finished.emit(counter)
def f(assertEqual, priority): assertEqual(QThread.currentThread().priority(), priority)
def f1(): em2 = Emitter() with WaitForSignal(em2.bing, 1000): ac.start(em2.g, lambda x: x, QThread.currentThread()) self.assertEqual(em2.thread, em2.result)
def messageHandler(msgType, *args): """ Module function handling messages. @param msgType type of the message (integer, QtMsgType) @param args message handler arguments, for PyQt4 message to be shown (bytes), for PyQt5 context information (QMessageLogContext) and message to be shown (bytes) """ if len(args) == 2: context = args[0] message = args[1] else: message = args[0] if __msgHandlerDialog: try: if msgType == QtDebugMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Debug Message:") elif msgType == QtWarningMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Warning:") elif msgType == QtCriticalMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Critical:") elif msgType == QtFatalMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Fatal Error:") if isinstance(message, bytes): message = Utilities.decodeBytes(message) message = message.replace("\r\n", "<br/>")\ .replace("\n", "<br/>")\ .replace("\r", "<br/>") if len(args) == 2: msg = "<p><b>{0}</b></p><p>{1}</p><p>File: {2}</p>" \ "<p>Line: {3}</p><p>Function: {4}</p>".format( messageType, Utilities.html_uencode(message), context.file, context.line, context.function) else: msg = "<p><b>{0}</b></p><p>{1}</p>".format( messageType, Utilities.html_uencode(message)) if QThread.currentThread() == qApp.thread(): __msgHandlerDialog.showMessage(msg) else: QMetaObject.invokeMethod( __msgHandlerDialog, "showMessage", Qt.QueuedConnection, Q_ARG(str, msg)) return except RuntimeError: pass elif __origMsgHandler: __origMsgHandler(msgType, message) return if msgType == QtDebugMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Debug Message") elif msgType == QtWarningMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Warning") elif msgType == QtCriticalMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Critical") elif msgType == QtFatalMsg: messageType = QCoreApplication.translate( "E5ErrorMessage", "Fatal Error") if isinstance(message, bytes): message = message.decode() if len(args) == 2: print("{0}: {1} in {2} at line {3} ({4})".format( messageType, message, context.file, context.line, context.function)) else: print("{0}: {1}".format(messageType, message))