當前位置: 首頁>>代碼示例>>Python>>正文


Python asyncio.QueueEmpty方法代碼示例

本文整理匯總了Python中asyncio.QueueEmpty方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.QueueEmpty方法的具體用法?Python asyncio.QueueEmpty怎麽用?Python asyncio.QueueEmpty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.QueueEmpty方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def get(self) -> ParsedAnswer:

        try:
            item = self._queue.get_nowait()
        except asyncio.QueueEmpty:
            item = await self._queue.get()

        self._queue.task_done()

        # If we receive an exception when reading the queue, we raise it
        if isinstance(item, Exception):
            self._closed = True
            raise item

        # Don't need to save new answers or
        # send the stop message if we already received the complete message
        answer_type, execution_result = item
        if answer_type == "complete":
            self.send_stop = False
            self._closed = True

        return item 
開發者ID:graphql-python,項目名稱:gql,代碼行數:24,代碼來源:websockets.py

示例2: get_available_candidate

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def get_available_candidate(self) -> discord.TextChannel:
        """
        Return a dormant channel to turn into an available channel.

        If no channel is available, wait indefinitely until one becomes available.
        """
        log.trace("Getting an available channel candidate.")

        try:
            channel = self.channel_queue.get_nowait()
        except asyncio.QueueEmpty:
            log.info("No candidate channels in the queue; creating a new channel.")
            channel = await self.create_dormant()

            if not channel:
                log.info("Couldn't create a candidate channel; waiting to get one from the queue.")
                await self.notify()
                channel = await self.wait_for_dormant_channel()

        return channel 
開發者ID:python-discord,項目名稱:bot,代碼行數:22,代碼來源:help_channels.py

示例3: receive_until

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def receive_until(self, monotonic_deadline: float) -> typing.Optional[pyuavcan.transport.TransferFrom]:
        try:
            timeout = monotonic_deadline - self._loop.time()
            if timeout > 0:
                transfer = await asyncio.wait_for(self._queue.get(), timeout, loop=self._loop)
            else:
                transfer = self._queue.get_nowait()
        except (asyncio.TimeoutError, asyncio.QueueEmpty):
            # If there are unprocessed transfers, allow the caller to read them even if the instance is closed.
            if self._maybe_finalizer is None:
                raise pyuavcan.transport.ResourceClosedError(f'{self} is closed')
            return None
        else:
            assert isinstance(transfer, pyuavcan.transport.TransferFrom), 'Internal protocol violation'
            assert transfer.source_node_id == self._specifier.remote_node_id or self._specifier.remote_node_id is None
            return transfer 
開發者ID:UAVCAN,項目名稱:pyuavcan,代碼行數:18,代碼來源:_input.py

示例4: main

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def main(self):
        print('start')
        async_q = self._queue.async_q
        main_loop = asyncio.get_event_loop()
        while not (self._stopped and async_q.empty()):

            try:
                event = self.queue.get_nowait()
            except asyncio.QueueEmpty:
                pass
            else:
                asyncio.run_coroutine_threadsafe(
                    self.event_hadler(event),
                    main_loop
                )
                async_q.task_done()
            await asyncio.sleep(0.0001) 
開發者ID:QUANTAXIS,項目名稱:QUANTAXIS,代碼行數:19,代碼來源:QAAsyncThread.py

示例5: __handle_queue_update

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def __handle_queue_update(cls,
                              q: Union[queue.Queue, asyncio.Queue],
                              first: object) -> list:
        ret = first if isinstance(first, list) else [first]

        while True:
            try:
                elem = q.get_nowait()
                if isinstance(elem, list):
                    ret.extend(elem)
                else:
                    ret.append(elem)
            except (asyncio.QueueEmpty, queue.Empty):
                break

        return ret 
開發者ID:goldmansachs,項目名稱:gs-quant,代碼行數:18,代碼來源:risk.py

示例6: _stream_protocol_messages

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def _stream_protocol_messages(self,
                                        protocol_class: Type[ProtocolAPI],
                                        ) -> AsyncIterator[CommandAPI[Any]]:
        """
        Stream the messages for the specified protocol.
        """
        async with self._protocol_locks[protocol_class]:
            self.raise_if_streaming_error()
            msg_queue = self._protocol_queues[protocol_class]
            while self.is_streaming:
                try:
                    # We use an optimistic strategy here of using
                    # `get_nowait()` to reduce the number of times we yield to
                    # the event loop.  Since this is an async generator it will
                    # yield to the loop each time it returns a value so we
                    # don't have to worry about this blocking other processes.
                    yield msg_queue.get_nowait()
                except asyncio.QueueEmpty:
                    yield await msg_queue.get()

    #
    # Message reading and streaming API
    # 
開發者ID:ethereum,項目名稱:trinity,代碼行數:25,代碼來源:multiplexer.py

示例7: raise_errors

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def raise_errors(self):
        # If the error monitor is running then just return, as that means we are
        # running as a worker and so can rely on the error monitor to pickup the
        # errors which an happen in the various background tasks
        if self._error_monitor_lock.locked():
            return

        # Check queue for errors
        try:
            error: Error = self.error_queue.get_nowait()
        except asyncio.QueueEmpty:
            # No errors, everything ok
            return
        else:
            # If there is an error then raise it
            raise error.value 
開發者ID:adamcharnock,項目名稱:lightbus,代碼行數:18,代碼來源:bus_client.py

示例8: run

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def run(self, *args):
        while True:
            msg = await self.queue.get()
            async with self.get_connection() as conn:
                self.connect_counter += 1
                while True:
                    try:
                        await self.send_message(msg, conn)
                        self.mail_success += 1
                    except:
                        self.mail_failed += 1
                        await conn.close()
                        logger.exception('Mailer reconnect')
                        self.reconnect_counter += 1
                        await asyncio.sleep(2)
                        await conn.open()
                    try:
                        msg = self.queue.get_nowait()
                    except asyncio.QueueEmpty:
                        break 
開發者ID:dvhb,項目名稱:dvhb-hybrid,代碼行數:22,代碼來源:base.py

示例9: get

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def get(
        self, *, no_ack=False, fail=True, timeout=5
    ) -> Optional[IncomingMessage]:

        """ Get message from the queue.

        :param no_ack: if :class:`True` you don't need to call
                       :func:`aio_pika.message.IncomingMessage.ack`
        :param timeout: execution timeout
        :param fail: Should return :class:`None` instead of raise an
                     exception :class:`aio_pika.exceptions.QueueEmpty`.
        :return: :class:`aio_pika.message.IncomingMessage`
        """

        msg = await asyncio.wait_for(
            self.channel.basic_get(self.name, no_ack=no_ack), timeout=timeout,
        )  # type: Optional[DeliveredMessage]

        if msg is None:
            if fail:
                raise QueueEmpty
            return

        return IncomingMessage(msg, no_ack=no_ack) 
開發者ID:mosquito,項目名稱:aio-pika,代碼行數:26,代碼來源:queue.py

示例10: close

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def close(self):
        if not self._consumer_tag:
            return

        await self._amqp_queue.cancel(self._consumer_tag)
        self._consumer_tag = None

        def get_msg():
            try:
                return self._queue.get_nowait()
            except asyncio.QueueEmpty:
                return

        # Reject all messages
        msg = get_msg()  # type: IncomingMessage
        while msg and not self._amqp_queue.channel.closing.done():
            await msg.reject(requeue=True)
            msg = get_msg()  # type: IncomingMessage 
開發者ID:mosquito,項目名稱:aio-pika,代碼行數:20,代碼來源:queue.py

示例11: poll

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def poll(self):
        """Wait for packets to send to the client."""
        try:
            packets = [await asyncio.wait_for(self.queue.get(),
                                              self.server.ping_timeout)]
            self.queue.task_done()
        except (asyncio.TimeoutError, asyncio.CancelledError):
            raise exceptions.QueueEmpty()
        if packets == [None]:
            return []
        while True:
            try:
                pkt = self.queue.get_nowait()
                self.queue.task_done()
                if pkt is None:
                    self.queue.put_nowait(None)
                    break
                packets.append(pkt)
            except asyncio.QueueEmpty:
                break
        return packets 
開發者ID:miguelgrinberg,項目名稱:python-engineio,代碼行數:23,代碼來源:asyncio_socket.py

示例12: handle_get_request

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def handle_get_request(self, environ):
        """Handle a long-polling GET request from the client."""
        connections = [
            s.strip()
            for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        transport = environ.get('HTTP_UPGRADE', '').lower()
        if 'upgrade' in connections and transport in self.upgrade_protocols:
            self.server.logger.info('%s: Received request to upgrade to %s',
                                    self.sid, transport)
            return await getattr(self, '_upgrade_' + transport)(environ)
        if self.upgrading or self.upgraded:
            # we are upgrading to WebSocket, do not return any more packets
            # through the polling endpoint
            return [packet.Packet(packet.NOOP)]
        try:
            packets = await self.poll()
        except exceptions.QueueEmpty:
            exc = sys.exc_info()
            await self.close(wait=False)
            six.reraise(*exc)
        return packets 
開發者ID:miguelgrinberg,項目名稱:python-engineio,代碼行數:23,代碼來源:asyncio_socket.py

示例13: _consume

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def _consume(
        self,
        payload_queue: asyncio.Queue,
        request_meta: Optional[RequestMeta] = None,
        add_start_dispatch: Optional[List[str]] = None,
    ) -> None:
        while True:
            try:
                task = await payload_queue.get()
                # Determine whether the provider has returned a `Payload`, or a task.
                # If it is a task, load the defined archiver plugin to load the
                # `Payload`, otherwise, simply continue on with the scanning.
                if isinstance(task, Payload):
                    request = Request([task], request_meta)
                    await self.scan_request(request, add_start_dispatch)
                else:
                    for source_archiver, task_meta in task.items():
                        self.log.debug(
                            f'Provider task received: source_archiver: {source_archiver}, '
                            f'task_meta: {task_meta}'
                        )
                        try:
                            ar = ArchiverResponse(task_meta)
                            payload = await self._loaded_source_archiver_plugins[
                                source_archiver
                            ].get(ar)
                            if payload:
                                request = Request([payload], request_meta)
                                await self.scan_request(request, add_start_dispatch)
                        except Exception as e:
                            self.log.warn(
                                f'"{task_meta}" failed with archiver "{source_archiver}": {str(e)}'
                            )
                payload_queue.task_done()
            except asyncio.QueueEmpty:
                pass 
開發者ID:PUNCH-Cyber,項目名稱:stoq,代碼行數:38,代碼來源:core.py

示例14: next

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def next(self):
        if self.users.empty():
            await self.fill_users()

        try:
            return self.users.get_nowait()
        except asyncio.QueueEmpty:
            raise NoMoreItems() 
開發者ID:Rapptz,項目名稱:discord.py,代碼行數:10,代碼來源:iterators.py

示例15: async_test

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import QueueEmpty [as 別名]
def async_test(timeout=1):
    func = None
    if callable(timeout):
        func = timeout
        timeout = 1

    def _decorator(f):
        @functools.wraps(f)
        def _wrapper(self, *args, **kwargs):
            task = self.loop.create_task(
                asyncio.coroutine(f)(self, *args, **kwargs))

            def _cancel():
                task.print_stack()
                task.cancel()

            time_handle = self.loop.call_later(timeout, _cancel)
            try:
                return self.loop.run_until_complete(task)
            except asyncio.CancelledError:
                events = []
                while True:
                    try:
                        events.append(self.server.events.get_nowait())
                    except asyncio.QueueEmpty:
                        break
                self.fail('server events: {}'.format(events))
            finally:
                time_handle.cancel()

        return _wrapper

    if func is not None:
        return _decorator(func)

    return _decorator 
開發者ID:decentfox,項目名稱:aioh2,代碼行數:38,代碼來源:__init__.py


注:本文中的asyncio.QueueEmpty方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。