How to iterate Queue.Queue items in Python? How to iterate Queue.Queue items in Python? python python

How to iterate Queue.Queue items in Python?


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

for elem in list(q.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


Listing queue elements without consuming them:

>>> from Queue import Queue>>> q = Queue()>>> q.put(1)>>> q.put(2)>>> q.put(3)>>> print list(q.queue)[1, 2, 3]

After operation, you can still process them:

>>> q.get()1>>> print list(q.queue)[2, 3]


You can subclass queue.Queue to achieve this in a thread-safe way:

import queueclass 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)