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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…