How to iterate Queue.Queue items in Python?

前端 未结 3 1890
傲寒
傲寒 2020-12-28 12:40

Does anyone know a pythonic way of iterating over the elements of a Queue.Queue without removing them from the Queue. I have a producer/consumer-type p

3条回答
  •  情书的邮戳
    2020-12-28 12:45

    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
    

提交回复
热议问题