![](/img/trans.png)
[英]How to iterate through a Python Queue.Queue with a for loop instead of a while loop?
[英]python loop a queue without while
我现在正在使用Python 2.7中的多处理和队列,并尝试使用变量p打印0到7。 当while
用作选项1中显示的注释代码时,它可以工作。 但是当使用for
和iter()
,如选项2所示,0到7会打印,但程序永远不会退出循环,我必须手动退出。 关于如何修改代码以便在打印后正常退出循环的任何建议? 使用iter()
,有没有办法为输入arg p.get
设置block=False
?
def try_queue():
q = Queue()
for i in range(10):
q.put(i)
p = Queue()
for j in iter(q.get,8):
p.put(j)
# option 1, use while, works.
# while not p.empty():
# print(p.get())
# option 2, use iter()
for k in iter(p.get, None): # None is the sentinel here
print(k)
try_queue()
您无法轻松实现这一点,因为Queue
不支持迭代器协议 。 原因是Queue
被设计为消息传递对象而不是容器。
Queue.get
方法不能确保Queue
实际为空 。 因此,在编写逻辑时请记住这一点:这不是Queue
使用方式。 把它想象成线程/进程之间的一种“套接字”。
这有两种方法可以达到你想要的效果。
1)创建一个支持迭代器协议的IterQueue
类。
from Queue import Queue
class IterQueue(Queue):
"""Queue supporting iterator protocol."""
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration()
return self.get()
queue = IterQueue()
for element in queue:
print element
2)将get调用包装到生成器中。 这在技术上隐藏了逻辑中的while循环。
def get_next_element(queue):
while not queue.empty():
yield queue.get()
for element in get_next_element(queue):
print element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.