当前位置: 首页>>代码示例>>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;未经允许,请勿转载。