【问题标题】:How to iterate Queue.Queue items in Python?如何在 Python 中迭代 Queue.Queue 项目?
【发布时间】:2012-01-02 00:48:23
【问题描述】:

有谁知道迭代Queue.Queue 的元素的pythonic 方式 从队列中删除它们。我有一个生产者/消费者类型的程序,其中要处理的项目通过使用Queue.Queue 传递,并且我希望能够打印剩余的项目是什么。有什么想法吗?

【问题讨论】:

    标签: python queue producer-consumer


    【解决方案1】:

    您可以遍历底层数据存储的副本:

    for elem in list(q.queue)
    

    尽管这绕过了 Queue 对象的锁,但列表副本是一个原子操作,它应该可以正常工作。

    如果您想保留锁,为什么不将所有任务从队列中拉出,复制您的列表,然后将它们放回原处。

    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
    

    【讨论】:

    • for elem in list(q.queue) 在 Python 3 中导致 TypeError: 'Queue' object is not iterable。也许我做错了什么?
    • @macmadness86 看起来你有另一个层,“q”是代码对象,它有一个包含队列对象的“队列”属性。试试这个:for elem in list(q.queue.queue).
    • 罗杰。会遵守。谢谢你的提示。 (此消息计划删除)
    【解决方案2】:

    您可以继承 queue.Queue 以线程安全的方式实现这一点:

    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)
    

    【讨论】:

      【解决方案3】:

      列出队列元素而不使用它们:

      >>> from Queue import Queue
      >>> q = Queue()
      >>> q.put(1)
      >>> q.put(2)
      >>> q.put(3)
      >>> print list(q.queue)
      [1, 2, 3]
      

      操作后,您仍然可以处理它们:

      >>> q.get()
      1
      >>> print list(q.queue)
      [2, 3]
      

      【讨论】:

        【解决方案4】:

        您可以在打印元素之前将双端队列转换为列表,以便您可以轻松地遍历它。

        from collections import deque
        
        d = deque([7,9,3,5])
        
        d.append(2)
        d.appendleft(1)
        d.append(10)
        d.pop()
        
        for elem in list(d):
            print(elem, end=" ")
        
        #Output: 1 7 9 3 5 2 
        

        【讨论】:

          猜你喜欢
          • 2017-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-30
          • 2014-01-15
          • 1970-01-01
          • 2021-03-07
          • 2016-04-25
          相关资源
          最近更新 更多