def _processPendingEvents(): """Process pending application events.""" # Create an event loop to run in. Otherwise, we need to use the # QApplication main loop, which may already be running and therefore # unusable. qe = QEventLoop() # Create a single-shot timer. Could use QTimer.singleShot(), # but can't cancel this / disconnect it. timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(qe.quit) timer.start(1) # Wait for an emitted signal. qe.exec_() # Clean up: don't allow the timer to call qe.quit after this # function exits, which would produce "interesting" behavior. timer.stop() # Stopping the timer may not cancel timeout signals in the # event queue. Disconnect the signal to be sure that loop # will never receive a timeout after the function exits. timer.timeout.disconnect(qe.quit)
def download_file(self, url, path_file): """ download function :param url: url path of file :param path_file: path to save file :return: """ self.file_install = path_file self.url = url loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(lambda: loop.exit(1)) timer.start(100000) # 10 second time-out # req = QNetworkRequest(QUrl('https://www.python.org/')) req = QNetworkRequest(QUrl(url)) result = self.manager.get(req) result.finished.connect(lambda: self.fin_req(loop, result)) self.print_('fetching request...', self.dbg) if loop.exec_() == 0: timer.stop() self.print_( '{} is received: {}'.format(os.path.basename(path_file), result.readAll().count()), self.dbg) else: self.print_('request timed-out')
def query(self, query): """ Perform a nominatim query @param query: Query to execute @type query: str @raise NetWorkErrorException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url) query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('q', query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: return json.loads(self.data) else: raise NetWorkErrorException(suffix="Nominatim API")
def run(self): time = QTime() eventLoop = QEventLoop() self.m_bStop = False # log.debug("Запускаем поток") #if not self.initThread(): #return while not self.m_bStop: self.m_nTactCounter += 1 # Добавить обнуление при переполнении time.start() eventLoop.processEvents() if not self.workThread(): self.m_bStop = True return workTime = time.elapsed() if 0 <= workTime < self.m_nTact: self.msleep(self.m_nTact - workTime) else: self.msleep(0) eventLoop.processEvents() self.exitThread()
def call_method(self, method, *args, **kwargs): """Call a method.""" callback = kwargs.get('callback') if callback is not None: super(QtMessageBusConnection, self).call_method(method, *args, **kwargs) return replies = [] loop = QEventLoop() def _store_reply(message): replies.append(message) loop.quit() kwargs['callback'] = _store_reply super(QtMessageBusConnection, self).call_method(method, *args, **kwargs) mask = QEventLoop.ExcludeUserInputEvents | QEventLoop.WaitForMoreEvents while True: loop.processEvents(mask) if replies: break reply = replies[0] if 'error' in reply: raise MessageBusError(reply['error']['code'], reply['error'].get('data')) return reply.get('result')
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 load(self): worker = CartoDBPluginWorker(self, 'loadLayer') worker.error.connect(self.workerError) self.loop = QEventLoop() worker.finished.connect(self.workerFinished) worker.start() self.loop.exec_()
def __sync_request(self, url): _url = QUrl(url) _request = QNetworkRequest(_url) self.__replies.append(_request) QgsNetworkAccessManager.instance().sslErrors.connect( self.__supress_ssl_errors) _reply = QgsNetworkAccessManager.instance().get(_request) # wait loop = QEventLoop() _reply.finished.connect(loop.quit) loop.exec_() _reply.finished.disconnect(loop.quit) QgsNetworkAccessManager.instance().sslErrors.disconnect( self.__supress_ssl_errors) loop = None error = _reply.error() if error != QNetworkReply.NoError: raise Exception(error) result_code = _reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) result = _reply.readAll() self.__replies.append(_reply) _reply.deleteLater() if result_code in [301, 302, 307]: redirect_url = _reply.attribute( QNetworkRequest.RedirectionTargetAttribute) return self.__sync_request(redirect_url) else: return result
def download(self, sql): apiUrl = 'http://{}.{}/api/v2/sql?api_key={}&format=spatialite&q={}'.format( self.cartodbUser, self.hostname, self.apiKey, sql) url = QUrl(apiUrl) request = self._getRequest(url) def finished(reply): tempdir = tempfile.tempdir if tempdir is None: tempdir = tempfile.mkdtemp() tf = tempfile.NamedTemporaryFile(delete=False) sqlite = QFile(tf.name) tf.close() if (sqlite.open(QIODevice.WriteOnly)): sqlite.write(reply.readAll()) sqlite.close() self.fetchContent.emit(tf.name) else: self.error.emit('Error saving downloaded file') manager = QNetworkAccessManager() manager.finished.connect(finished) reply = manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def waitForSignal(signal, message="", timeout=0): """Waits (max timeout msecs if given) for a signal to be emitted. It the waiting lasts more than 2 seconds, a progress dialog is displayed with the message. Returns True if the signal was emitted. Return False if the wait timed out or the dialog was canceled by the user. """ loop = QEventLoop() dlg = QProgressDialog(minimum=0, maximum=0, labelText=message) dlg.setWindowTitle(appinfo.appname) dlg.setWindowModality(Qt.ApplicationModal) QTimer.singleShot(2000, dlg.show) dlg.canceled.connect(loop.quit) if timeout: QTimer.singleShot(timeout, dlg.cancel) stop = lambda: loop.quit() signal.connect(stop) loop.exec_() signal.disconnect(stop) dlg.hide() dlg.deleteLater() return not dlg.wasCanceled()
def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_()
def OeQ_wait_for_renderer(timeout=10000): """Block loop until signal emitted, or timeout (ms) elapses.""" from PyQt4.QtCore import QEventLoop, QTimer #print 'wait for renderer...', # function call if action timed out def timed_out(render_result_flag): render_result_flag[0] = False loop.quit() #define loop loop = QEventLoop() #define Timer timer = QTimer() #define render_result render_result = [True] OeQ_wait(2) #check wether Canvas is drawing if iface.mapCanvas().isDrawing(): #connect mapCanvasRefreshed and renderComplete events to quit loop iface.mapCanvas().renderComplete.connect(loop.quit) iface.mapCanvas().mapCanvasRefreshed.connect(loop.quit) # if a timeout is defined and other than 0 if bool(timeout): # start timer timer.singleShot(timeout, lambda: timed_out(render_result)) #and jump into the loop loop.exec_() #disconnect after loop has quit iface.mapCanvas().mapCanvasRefreshed.disconnect(loop.quit) iface.mapCanvas().renderComplete.disconnect(loop.quit) #print 'Done' return render_result[0]
def quit(self): loop = QEventLoop() reply = self._make_request('quit') reply.finished.connect(loop.quit) loop.exec_() QThread.quit(self)
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 cbUserData(self, data): if 'error' in data: # TODO Create image for error self.nameLB.setText( "<html><head/><body><p><span style=\" text-decoration: underline; color:red;\">error</span></p></body></html>" ) self.error.emit(data['error']) return self.currentUserData = data self.settings.setValue('/CartoDBPlugin/selected', self.currentUser) manager = QNetworkAccessManager() manager.finished.connect(self.returnAvatar) if 's3.amazonaws.com' in data['avatar_url']: imageUrl = QUrl(data['avatar_url']) else: imageUrl = QUrl('http:' + data['avatar_url']) request = QNetworkRequest(imageUrl) request.setRawHeader('User-Agent', 'QGIS 2.x') reply = manager.get(request) loop = QEventLoop() reply.finished.connect(loop.exit) loop.exec_()
def getUserTables(self, page=1, per_page=20, shared='yes', returnDict=True): self.returnDict = returnDict payload = { 'tag_name': '', 'q': '', 'page': page, 'type': '', 'exclude_shared': 'false', 'per_page': per_page, 'tags': '', 'shared': shared, 'locked': 'false', 'only_liked': 'false', 'order': 'name', 'types': 'table' } url = QUrl( self.apiUrl + "viz?api_key={}&{}".format(self.apiKey, urllib.urlencode(payload))) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
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 wait_input(self, prompt=''): """Wait for input (raw_input support)""" self.new_prompt(prompt) self.setFocus() self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None
def wait_input(self): """Wait for input (raw_input)""" self.input_data = None # If shell is closed, None will be returned self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None return self.input_data
def exec_(self): self.show() e = QEventLoop() self.eventLoop = e e.exec_() self.eventLoop = None
def DownLoadOverQT(dlURL, LokFileName): def WriteFile(LokFileName, content): if path.exists(LokFileName): remove(LokFileName) out = open(LokFileName, 'wb') out.write(content) out.close() def onfinish(): WriteFile(LokFileName, reply.readAll()) loop.quit() request = QNetworkRequest() request.setUrl(QUrl(dlURL)) manager = QgsNetworkAccessManager.instance() reply = manager.get(request) reply.setParent(None) loop = QEventLoop() reply.finished.connect(onfinish) loop.exec_() status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) if (status == 301): redirectUrl = reply.attribute(request.RedirectionTargetAttribute) request = QNetworkRequest() request.setUrl(redirectUrl) manager = QgsNetworkAccessManager.instance() reply = manager.get(request) reply.setParent(None) loop = QEventLoop() reply.finished.connect(onfinish) loop.exec_() if path.exists(LokFileName): return path.getsize(LokFileName), reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) else: return None, reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) reply.deleteLater()
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 _createWebAppCompiled(n): from pubsub import pub def endWriteWebAppListener(success, reason): from pubsub import pub pub.unsubscribe(endWriteWebAppListener, topics.endWriteWebApp) loop.exit() loop = QEventLoop() pub.subscribe(endWriteWebAppListener , topics.endWriteWebApp) _createWebApp(n, False) loop.exec_(flags = QEventLoop.ExcludeUserInputEvents)
def quit(self): if self.io_conn and self.io_conn.state() == QTcpSocket.ConnectedState: loop = QEventLoop() self.io_conn.disconnected.connect(loop.quit) self.io_conn.disconnectFromHost() self.log.debug("Entered disconnect state...") if self.io_conn.state() == QTcpSocket.ConnectedState: loop.exec_() self.log.info("Done") Connection.quit(self)
def __enter__(self): # Create an event loop to run in. Otherwise, we need to use the papp # (QApplication) main loop, which may already be running and therefore # unusable. self.qe = QEventLoop() # Connect both signals to a slot which quits the event loop. self.signal.connect(self.signalSlot) return self
def _wait_signal(signal, timeout=None): """Block loop until signal emitted, or timeout (ms) elapses.""" # http://jdreaver.com/posts/2014-07-03-waiting-for-signals-pyside-pyqt.html loop = QEventLoop() signal.connect(loop.quit) yield if timeout is not None: QTimer.singleShot(timeout, loop.quit) loop.exec_()
def checkUploadStatus(self, id, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "imports/{}/?api_key={}".format(id, self.apiKey)) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def updateViz(self, viz, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "viz/{}?api_key={}".format(viz['id'], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(viz)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def updateLayerInMap(self, mapId, layer, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "maps/{}/layers/{}?api_key={}".format( mapId, layer['id'], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(layer)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def getLayersMap(self, mapId, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "maps/{}/layers?api_key={}".format(mapId, self.apiKey)) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()