Mokus
Mokus

Reputation: 10400

Clear all items from the queue

How can I clear a queue. For example I have datas in a queue, but for some reason I don't need the existing data, and just want to clear the queue.

Is there any way? Will this work:

oldQueue = Queue.Queue()

Upvotes: 87

Views: 140726

Answers (5)

Ronan Paixão
Ronan Paixão

Reputation: 8685

Using only the public API:

try:
    while True:
        self.queue.get(False)
except queue.Empty:
    pass

Upvotes: 1

Muhammad Shahbaz
Muhammad Shahbaz

Reputation: 365

If you just want an empty queue, and don't care about garbage collection of the older queue, simply instantiate a new queue using the same handle. For example,

    q = Queue(maxsize=max_size)
    q.put(1)
    q.put(2)
    q.put(3)
    q.put(4)

Now in order to make this queue empty, you can simply write the following.

    q = Queue(maxsize=max_size)

And at this point you should have an empty queue.

Upvotes: -1

V.E.O
V.E.O

Reputation: 923

You just can not clear the queue, because every put also add the unfinished_tasks member. The join method depends on this value. And all_tasks_done needs to be notified also.

with q.mutex:
    q.queue.clear()
    q.all_tasks_done.notify_all()
    q.unfinished_tasks = 0

or in decent way, use get and task_done pair to safely clear the tasks.

    while not q.empty():
        try:
            q.get(block=False)
        except Empty:
            continue
        q.task_done()

or just create a new Queue and delete old one.

Upvotes: 49

Niklas R
Niklas R

Reputation: 16870

This seems to do it pretty well for me. I welcome comments/additions in case I missed anything important.

class Queue(queue.Queue):
  '''
  A custom queue subclass that provides a :meth:`clear` method.
  '''

  def clear(self):
    '''
    Clears all items from the queue.
    '''

    with self.mutex:
      unfinished = self.unfinished_tasks - len(self.queue)
      if unfinished <= 0:
        if unfinished < 0:
          raise ValueError('task_done() called too many times')
        self.all_tasks_done.notify_all()
      self.unfinished_tasks = unfinished
      self.queue.clear()
      self.not_full.notify_all()

Upvotes: 12

Rob Cowie
Rob Cowie

Reputation: 22619

q = Queue.Queue()
q.queue.clear()

EDIT I omitted the issue of thread safety for clarity and brevity, but @Dan D is quite correct, the following is better.

q = Queue.Queue()
with q.mutex:
    q.queue.clear()

Upvotes: 137

Related Questions