Python asyncio 模块,QueueEmpty() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用asyncio.QueueEmpty()

项目:aiolirc    作者:pylover    | 项目源码 | 文件源码
def test_via_emulator(self):

        amp_power_call_count = 0
        amp_source_call_count = 0

        @listen_for('amp power', repeat=5)
        async def amp_power(loop):
            nonlocal amp_power_call_count
            amp_power_call_count += 1

        @listen_for('amp source', repeat=5)
        async def amp_source(loop):
            nonlocal amp_source_call_count
            amp_source_call_count += 1

        async with EmulatedClient() as client:
            dispatcher = IRCDispatcher(client)

            try:
                await dispatcher.listen()
            except asyncio.QueueEmpty:
                print('Test Done')

        self.assertGreaterEqual(amp_power_call_count, 1)
        self.assertGreaterEqual(amp_source_call_count, 1)
项目:aiolirc    作者:pylover    | 项目源码 | 文件源码
def test_via_emulator(self):
        async with EmulatedClient(check_interval=.01) as client:
            for i in range(10):
                self.assertEqual(await client.__anext__(), 'amp power')

            for i in range(5):
                self.assertEqual(await client.__anext__(), 'amp source')

            for i in range(5):
                self.assertEqual(await client.__anext__(), 'off')

            for i in range(2):
                self.assertEqual(await client.__anext__(), 'amp source')

            async with client.ignore():
                await asyncio.sleep(.1)

            await self.assertRaises(asyncio.QueueEmpty, client.__anext__)
项目:RealtimePythonChat    作者:quangtqag    | 项目源码 | 文件源码
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 IOError()
        if packets == [None]:
            return []
        try:
            packets.append(self.queue.get_nowait())
            self.queue.task_done()
        except asyncio.QueueEmpty:
            pass
        return packets
项目:async_face_recognition    作者:dpdornseifer    | 项目源码 | 文件源码
def _returnfaces(self, request):
        ''' returnes the processed images with the detected artifacts highlighted '''
        try:

            image = yield from self._getlastimage()

            image_buf = cv2.imencode('.jpg', image)[1]
            image_str = np.array(image_buf).tostring()

        except asyncio.QueueEmpty as qe:
            msg = 'QueueEmpty exception has been thrown. There is no image ' \
                  'with some recognized artifacts in the queue right now.'
            self._logger.warning(msg)
            return Response(
                text=msg,
                status=500,
                content_type='application/json'
            )


        return Response(
            body=image_str,
            status=200,
            content_type='image/jpeg'
        )
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_nonblocking_get_exception(self):
        q = asyncio.Queue(loop=self.loop)
        self.assertRaises(asyncio.QueueEmpty, q.get_nowait)
项目:aio-pika    作者:mosquito    | 项目源码 | 文件源码
def get(self, *, no_ack=False, timeout=None, fail=True) -> Generator[Any, None, 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`
        """

        f = self._create_future(timeout)

        def _on_getempty(method_frame, *a, **kw):
            if fail:
                f.set_exception(QueueEmpty(method_frame))
            else:
                f.set_result(None)

        def _on_getok(channel, envelope, props, body):
            message = IncomingMessage(
                channel,
                envelope,
                props,
                body,
                no_ack=no_ack,
            )

            f.set_result(message)

        with (yield from self._get_lock), self._channel.set_get_empty_callback(_on_getempty):
            log.debug("Awaiting message from queue: %r", self)

            self._channel.basic_get(_on_getok, self.name, no_ack=no_ack)

            try:
                message = yield from f
                return message
            finally:
                self._channel._on_getempty = None
项目:aio-pika    作者:mosquito    | 项目源码 | 文件源码
def _close(self):
        yield from 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:
            msg.reject(requeue=True)
            msg = get_msg()  # type: IncomingMessage
项目:asyncqlio    作者:SunDwarf    | 项目源码 | 文件源码
def close(self):
        """
        Closes the pool.
        """
        while True:
            try:
                conn = self.queue.get_nowait()
            except asyncio.QueueEmpty:
                return

            conn.close()
项目:tasky    作者:jreese    | 项目源码 | 文件源码
def run_task(self) -> None:
        '''Initialize the queue and spawn extra worker tasks if this if the
        first task.  Then wait for work items to enter the task queue, and
        execute the `run()` method with the current work item.'''

        while self.running:
            try:
                item = self.QUEUE.get_nowait()

                Log.debug('%s processing work item', self.name)
                await self.run(item)

                Log.debug('%s completed work item', self.name)
                self.QUEUE.task_done()

            except asyncio.QueueEmpty:
                if self.OPEN:
                    await self.sleep(0.05)

                else:
                    Log.debug('%s queue closed and empty, stopping', self.name)
                    return

            except CancelledError:
                Log.debug('%s cancelled, dropping work item')
                self.QUEUE.task_done()
                raise

            except Exception:
                Log.exception('%s failed work item', self.name)
                self.QUEUE.task_done()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_nonblocking_get_exception(self):
        q = asyncio.Queue(loop=self.loop)
        self.assertRaises(asyncio.QueueEmpty, q.get_nowait)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_nonblocking_get_exception(self):
        q = asyncio.Queue(loop=self.loop)
        self.assertRaises(asyncio.QueueEmpty, q.get_nowait)
项目:aioh2    作者:decentfox    | 项目源码 | 文件源码
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
项目:async_face_recognition    作者:dpdornseifer    | 项目源码 | 文件源码
def _getlastimage(self):
        ''' returns element from the image queue '''

        if not self._images.empty():
            image = yield from self._images.get()
            self._logger.info("getlastimage: Number of items still in the queue: {}".format(self._images.qsize()))
        else:
            # if empty raise QueueEmpty exception
            raise asyncio.QueueEmpty

        return image
项目:FlapJack-Cogs    作者:flapjax    | 项目源码 | 文件源码
def _queue_manager(self):
        await self.bot.wait_until_ready()
        while True:
            await asyncio.sleep(0.1)
            # First check for empty queues
            for slave in self.slave_tasks:
                if (self.slave_tasks[slave] is not None and
                        self.slave_tasks[slave].done()):
                    # Task is not completed until:
                    # Slave queue is empty, and timeout is reached /
                    # vc disconnected / someone else stole vc
                    self.slave_tasks[slave] = None
                    self.slave_queues[slave] = None

            # Next we can check for new items
            item = None
            try:
                item = self.master_queue.get_nowait()
            except asyncio.QueueEmpty:
                continue
            # This does not really check to make sure the queued item
            # is valid. Should probably check that with the enqueue function.
            channel = self.bot.get_channel(item['cid'])
            server = channel.server
            sid = server.id
            priority = item['priority']

            if self.slave_tasks.get(sid) is None:
                # Create slave queue
                queue = asyncio.Queue(maxsize=20)
                self.slave_queues[sid] = queue
                self.slave_tasks[sid] = self.bot.loop.create_task(
                                            self._slave_queue_manager(queue,
                                                                        sid))
            try:
                self.slave_queues[sid].put_nowait(item)
            except asyncio.QueueFull:
                # It's possible to add a way to handle full queue situation.
                pass
        # Need to add cancelled task exception handler?
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_udp(event_loop):
    """Simple UDP echo service."""

    host = '127.0.0.1'
    server_port = 5555
    client_port = 5556

    async def echo_server(iqueue, oqueue, loop):
        """UDP echo server."""

        try:
            while True:
                peer, data = await iqueue.get()
                assert peer == (host, client_port)
                await oqueue.put((peer, data))
        except asyncio.CancelledError:
            pass

    async def echo_client(iqueue, oqueue, loop):
        """UDP echo client."""

        # Repeatedly send until the server ACKs.
        item = None
        while item is None:
            try:
                item = iqueue.get_nowait()
            except asyncio.QueueEmpty:
                await asyncio.sleep(0.5, loop=loop)
                await oqueue.put(((host, server_port), b'PING'))

        peer, data = item
        assert peer == (host, server_port)
        assert data == b'PING'

    async with AsyncExitStack() as stack:
        server = await stack.enter_context(EnsureDone(
            udp_server(host, server_port, echo_server), loop=event_loop,
        ))
        client = await stack.enter_context(EnsureDone(
            udp_server(host, client_port, echo_client), loop=event_loop,
        ))
        await asyncio.wait_for(client, timeout=5.0, loop=event_loop)
        await cancel(server, loop=event_loop)

    assert client.result() is None
    assert server.result() is None