如果我使用python模块queue.Queue,我希望能够使用不弹出原始队列或创建新队列对象的方法打印出内容。
我试过尝试做一个获取,然后把内容放回去,但这是太高的成本。
# 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发布于 2019-02-12 18:26:06
>>> print(list(q.queue))这个对你有用吗?
发布于 2019-02-12 18:37:14
假设您正在使用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但是,除非您正在处理线程,否则我将使用一个普通列表作为队列实现。
发布于 2020-09-20 19:23:35
对不起,回答这个问题有点晚了,但是通过this comment,我根据您的要求在多处理包中扩展了队列。希望它能对未来的人有所帮助。
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的示例用法:
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,而且它似乎运行得很好。如果你认为这是可行的,或者在某些情况下可能失败,请告诉我。
https://stackoverflow.com/questions/54656387
复制相似问题