如何在Python中迭代Queue.Queue项目?
有谁知道迭代 Queue.Queue 元素的 Pythonic 方法,而不将它们从队列中删除。我有一个生产者/消费者类型的程序,其中要处理的项目是使用 Queue.Queue 传递的,并且我希望能够打印剩余的项目是什么。有什么想法吗?
Does anyone know a pythonic way of iterating over the elements of a Queue.Queue
without removing them from the Queue. I have a producer/consumer-type program where items to be processed are passed by using a Queue.Queue
, and I want to be able to print what the remaining items are. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以循环访问底层数据存储的副本:
尽管这绕过了队列对象的锁,但列表副本是一个原子操作,应该可以正常工作。
如果您想保留锁,为什么不将所有任务从队列中取出,复制列表,然后将它们放回去。
You can loop over a copy of the underlying data store:
Eventhough this bypasses the locks for Queue objects, the list copy is an atomic operation and it should work out fine.
If you want to keep the locks, why not pull all the tasks out of the queue, make your list copy, and then put them back.
列出队列元素而不消耗它们:
操作后,您仍然可以处理它们:
Listing queue elements without consuming them:
After operation, you can still process them:
您可以子类化
queue.Queue
以线程安全的方式实现此目的:You can subclass
queue.Queue
to achieve this in a thread-safe way:您可以在打印元素之前将双端队列转换为列表,以便可以轻松地迭代它。
You can convert the deque into a list before printing the elements so that you can easily iterate through it.
我已经实现了一个支持
async for
迭代的IterableQueue(asyncio.Queue)
。请参阅 pyutils 中的 GitHub。IterableQueue()
使用add_ Producer()
对生产者进行计数。一旦最后一个生产者完成(finish()
),那么一个哨兵值(None
)就会添加到队列中,标记队列结束。I have implemented an
IterableQueue(asyncio.Queue)
that supportsasync for
iteration. See pyutils in GitHub.IterableQueue()
counts producers withadd_producer()
. Once the last producers finishes (finish()
) then a sentinel value (None
) is added to the queue marking the queue end.