2011-11-19 68 views
16

有沒有人知道pythonic迭代方式的Queue.Queue而不是從隊列中刪除它們。我有一個生產者/消費者類型的程序,其中要處理的項目通過使用Queue.Queue來傳遞,我希望能夠打印剩餘項目。有任何想法嗎?如何迭代Python中的Queue.Queue項目?

回答

25

你也可以遍歷底層數據存儲的副本:

for elem in list(q.queue) 

Eventhough這種繞過鎖隊列對象,該列表的副本是一個原子操作,它應該工作了罰款。

如果你想保留鎖,爲什麼不把所有任務拉出隊列,讓你的列表複製,然後把它們放回去。

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 
+1

'列表中的元素(q.queue)'導致'TypeError:'隊列'對象在Python 3中不可迭代'。也許我做錯了什麼? –

+1

@ macmadness86它看起來像另一個圖層,「q」是代碼對象,具有包含隊列對象的「隊列」屬性。試試這個:''列表中的元素(q.queue.queue)''。 –

+0

羅傑。將遵守。謝謝你的提示。 (此消息計劃刪除) –

2

你也可以繼承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) 
0

上市隊列中的元素,而無需耗費他們:

>>> 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]