Python可迭代队列 [英] Python iterable Queue

查看:389
本文介绍了Python可迭代队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道队列何时关闭并且不会有更多项目,所以我可以结束迭代。

I need to know when a Queue is closed and wont have more items so I can end the iteration.

我是通过在队列中放置一个标记来实现的:

I did it by putting a sentinel in the queue:

from Queue import Queue

class IterableQueue(Queue): 

    _sentinel = object()

    def __iter__(self):
        return self

    def close(self):
        self.put(self._sentinel)

    def next(self):
        item = self.get()
        if item is self._sentinel:
            raise StopIteration
        else:
            return item

鉴于这是队列非常常见的用途,不存在任何内置实现?

Given that this is a very common use for a queue, isn't there any builtin implementation?

推荐答案

生成器是一种合理的方式,可以让生产者发送不再有队列任务的消息。

A sentinel is a reasonable way for a producer to send a message that no more queue tasks are forthcoming.

FWIW,您的代码可以通过 iter()

FWIW, your code can be simplified quite a bit with the two argument form of iter():

from Queue import Queue

class IterableQueue(Queue): 

    _sentinel = object()

    def __iter__(self):
        return iter(self.get, self._sentinel)

    def close(self):
        self.put(self._sentinel)

这篇关于Python可迭代队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆