繁体   English   中英

打印 Python 中队列的内容

[英]Printing contents of a Queue in Python

如果我使用 python 模块 queue.Queue,我希望能够使用不弹出原始队列或创建新队列 object 的方法打印出内容。

我曾尝试研究获取然后将内容放回原处,但这成本太高。

# Ideally it would look like the following
from queue import Queue
q = Queue()
q.print()
q.put(1)
q.print()

>> [] # Or something like this
>> [1] # Or something like this
>>> print(list(q.queue))

这对你有用吗?

假设你使用的是 python 2. 你可以使用这样的东西:

from queue import Queue
q = Queue.Queue()
q.put(1)
q.put(2)
q.put(3)
print q.queue

你也可以循环它:

for q_item in q.queue:
    print q_item

但是除非您正在处理线程,否则我会使用普通列表作为 Queue 实现。

抱歉,我回答这个问题有点晚了,但是通过此评论,我根据您的要求扩展了多处理包中的队列。 希望它会在将来对某人有所帮助。

import multiprocessing as mp
from multiprocessing import queues


class IterQueue(queues.Queue):

    def __init__(self, *args, **kwargs):
        ctx = mp.get_context()
        kwargs['ctx'] = ctx
        super().__init__(*args, **kwargs)

    # <----  Iter Protocol  ------>
    def __iter__(self):
        return self

    def __next__(self):
        try:
            if not self.empty():
                return self.get()  # block=True | default
            else:
                raise StopIteration
        except ValueError:  # the Queue is closed
            raise StopIteration

下面IterQueue我写的这个IterQueue的示例用法:

def sample_func(queue_ref):
    for i in range(10):
        queue_ref.put(i)


IQ = IterQueue()

p = mp.Process(target=sample_func, args=(IQ,))
p.start()
p.join()

print(list(IQ))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我已经针对一些更复杂的场景测试了这个IterQueue ,它似乎工作正常。 如果您认为这有效,或者在某些情况下可能会失败,请告诉我。

不确定这是否仍然是一个问题,但使用 name.queue(此处为 ieqqueue)对我有用。 这也适用于模块中的其他类型的队列。

import queue

q = queue.Queue() 

print(list(q.queue))
q.put(1)
print(list(q.queue))

如果您不使用队列,则最常用的打印队列内容的方法是使用以下代码片段:

class Queue:

    def __init__(self):
     self.items = []

 
    def push(self, e):
      self.items.append(e)
 
    def pop(self):
      head = self.items[0]
      self.items = self.item[1:]
      return head

    def print(self):
      for e in self.items:
          print(e)
q = Queue()
q.push(1)
q.push(23)
q.print()

输出

1
23

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM