I want to pull all the items currently in a queue. There is another thread constantly putting items in the other end, and every period I want to get all the items currently in the queue.
Is there some reason to prefer:
res = []
while q.qsize > 0 :
res.append(q.get())
or
res = []
while True :
try :
res.append(q.get(block=False))
except Queue.Empty :
break
Now the docs specifically say that the qsize() > 0 will not prevent the queue from blocking on a get, but is this true only in the case where multiple threads can take from the output?
Queue.qsize() Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.
Does this mean that the second form should always be preferred? EAFP and all that? Also, is there any cost to calling q.qsize()? Does it block the other end of the queue in order to count?
I guess I have talked myself into using the second form but it seems much less clean to me.