如何在 Python 中迭代 Queue.Queue 项目? [英] How to iterate Queue.Queue items in Python?

查看:74
本文介绍了如何在 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?

推荐答案

您可以遍历底层数据存储的副本:

You can loop over a copy of the underlying data store:

for elem in list(q.queue)

尽管这绕过了 Queue 对象的锁,但列表复制是一个原子操作,它应该可以正常工作.

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.

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

这篇关于如何在 Python 中迭代 Queue.Queue 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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