如何在Python中迭代Queue.Queue项?
有没有人知道用Python的方式来遍历一个Queue.Queue
里的元素,而不把它们从队列中移除?我有一个生产者/消费者类型的程序,处理的项目是通过Queue.Queue
传递的,我想打印出剩下的项目是什么。有什么好主意吗?
5 个回答
9
你可以通过创建一个queue.Queue
的子类来安全地实现这个功能,这样在多线程的情况下也不会出问题:
import queue
class ImprovedQueue(queue.Queue):
def to_list(self):
"""
Returns a copy of all items in the queue without removing them.
"""
with self.mutex:
return list(self.queue)
24
列出队列中的元素而不消耗它们:
>>> from Queue import Queue
>>> q = Queue()
>>> q.put(1)
>>> q.put(2)
>>> q.put(3)
>>> print list(q.queue)
[1, 2, 3]
操作之后,你仍然可以对它们进行处理:
>>> q.get()
1
>>> print list(q.queue)
[2, 3]
52
你可以遍历一份数据存储的副本:
for elem in list(q.queue)
虽然这样做可以绕过队列对象的锁,但复制列表是一个原子操作,应该没问题。
如果你想保持锁的机制,为什么不把队列里的所有任务取出来,先复制成列表,然后再放回去呢?
mycopy = []
while True:
try:
elem = q.get(block=False)
except Empty:
break
else:
mycopy.append(elem)
for elem in mycopy:
q.put(elem)
for elem in mycopy:
# do something with the elements