For that kind of queue, actually I would not typically use this check of queue.empty(), because I always use it in a threaded context and thus cannot know whether another thread would put something in there in a few milliseconds (thus that check would be useless anyway). I never check a queue for being empty. I rather use a sentinel value which marks the ending of a producer.
So using the iter(queue.get, Sentinel) is more what I like.
If you know that no other thread will put items in the queue anymore and just want to drain it from all currently contained items, then you can use something like this:
class Drainer(object):
def __init__(self, q):
self.q = q
def __iter__(self):
while True:
try:
yield self.q.get_nowait()
except queue.Empty: # On Python 2, use Queue.Empty
break
for item in Drainer(q):
print(item)
or
def drain(q):
while True:
try:
yield q.get_nowait()
except queue.Empty: # On Python 2, use Queue.Empty
break
for item in drain(q):
print(item)
queueare you using?