How to iterate Queue.Queue items in Python?

前端 未结 3 1880
傲寒
傲寒 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条回答
  •  Happy的楠姐
    2020-12-28 12:54

    You can subclass queue.Queue to achieve this in a thread-safe way:

    import queue
    
    
    class ImprovedQueue(queue.Queue):
        def to_list(self):
            """
            Returns a copy of all items in the queue without removing them.
            """
    
            with self.mutex:
                return list(self.queue)
    

提交回复
热议问题