Python: 从 PriorityQueue 中清除项目
Python: clear items from PriorityQueue
Clear all items from the queue
我看了上面的回答
我正在使用 python 2.7
import Queue
pq = Queue.PriorityQueue()
pq.clear()
我收到以下错误:
AttributeError: PriorityQueue instance has no attribute 'clear'
有没有办法轻松清空优先级队列而不是手动弹出所有项目?或者重新实例化工作(即它不会与 join() 混淆)?
实际上是pq.queue.clear()
。但是,正如您所引用问题的答案中所述,这没有记录在案并且可能不安全。
this answer中描述了最干净的方法:
while not q.empty():
try:
q.get(False)
except Empty:
continue
q.task_done()
重新实例化队列当然也可以(对象会简单地从内存中删除),只要您的代码的其他部分没有保留对旧队列的引用。
Clear all items from the queue
我看了上面的回答
我正在使用 python 2.7
import Queue
pq = Queue.PriorityQueue()
pq.clear()
我收到以下错误:
AttributeError: PriorityQueue instance has no attribute 'clear'
有没有办法轻松清空优先级队列而不是手动弹出所有项目?或者重新实例化工作(即它不会与 join() 混淆)?
实际上是pq.queue.clear()
。但是,正如您所引用问题的答案中所述,这没有记录在案并且可能不安全。
this answer中描述了最干净的方法:
while not q.empty():
try:
q.get(False)
except Empty:
continue
q.task_done()
重新实例化队列当然也可以(对象会简单地从内存中删除),只要您的代码的其他部分没有保留对旧队列的引用。