python不使用while循环队列
我现在在Python2.7中使用多处理和队列,并尝试使用变量p打印0到7。当python不使用while循环队列,python,queue,multiprocessing,Python,Queue,Multiprocessing,我现在在Python2.7中使用多处理和队列,并尝试使用变量p打印0到7。当而用作选项1中所示的注释代码时,它会起作用。但是,如选项2所示,使用for和iter()时,0到7会打印,但程序从未退出循环,我必须手动退出。关于如何修改代码以使循环在打印后正常退出,有何建议?使用iter(),是否有方法为输入argp.get设置block=False def try_queue(): q = Queue() for i in range(10): q.put(i)
而
用作选项1中所示的注释代码时,它会起作用。但是,如选项2所示,使用for
和iter()
时,0到7会打印,但程序从未退出循环,我必须手动退出。关于如何修改代码以使循环在打印后正常退出,有何建议?使用iter()
,是否有方法为输入argp.get
设置block=False
def try_queue():
q = Queue()
for i in range(10):
q.put(i)
p = Queue()
for j in iter(q.get,8):
p.put(j)
# option 1, use while, works.
# while not p.empty():
# print(p.get())
# option 2, use iter()
for k in iter(p.get, None): # None is the sentinel here
print(k)
try_queue()
您无法轻松实现这一点,因为
队列不支持。原因是队列
被设计为消息传递对象,而不是容器
Queue.get
方法不能确保Queue
是可用的。因此,在编写逻辑时请记住这一点:这不是使用队列的方式。将其更多地看作线程/进程之间的一种“套接字”
这里有两种方法可以实现你想要的
1) 创建一个支持迭代器协议的IterQueue
类
from Queue import Queue
class IterQueue(Queue):
"""Queue supporting iterator protocol."""
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration()
return self.get()
queue = IterQueue()
for element in queue:
print element
2) 将get调用封装到生成器中。这在技术上对您的逻辑隐藏了while循环
def get_next_element(queue):
while not queue.empty():
yield queue.get()
for element in get_next_element(queue):
print element
您无法轻松实现这一点,因为队列
不支持。原因是队列
被设计为消息传递对象,而不是容器
Queue.get
方法不能确保Queue
是可用的。因此,在编写逻辑时请记住这一点:这不是使用队列的方式。将其更多地看作线程/进程之间的一种“套接字”
这里有两种方法可以实现你想要的
1) 创建一个支持迭代器协议的IterQueue
类
from Queue import Queue
class IterQueue(Queue):
"""Queue supporting iterator protocol."""
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration()
return self.get()
queue = IterQueue()
for element in queue:
print element
2) 将get调用封装到生成器中。这在技术上对您的逻辑隐藏了while循环
def get_next_element(queue):
while not queue.empty():
yield queue.get()
for element in get_next_element(queue):
print element
我在其他地方用iter()做过实验,效果很好。只是不知道如何将它与queue.get()函数组合。另外,您确定要使用snychronized队列吗?也许你只是想在p:do_stuff(k)
中为k尝试一个deque
,它会报告TypeError:“Queue”对象是不可移植的
。是的,我正在学习多处理的东西,并在替换print(k)之前将其用作玩具试用
使用更复杂的代码。我认为不检查p.empty()
的for
循环将无法工作。使用默认设置block=True,timeout=None
,p.get
将只等待项目可用。它不会给你一个None
到StopIteration
。这就是为什么循环永远不会结束。我在其他地方用iter()做过实验,它是有效的。只是不知道如何将它与queue.get()函数组合。另外,您确定要使用snychronized队列吗?也许你只是想在p:do_stuff(k)
中为k尝试一个deque
,它会报告TypeError:“Queue”对象是不可移植的
。是的,我正在学习多处理的东西,并在替换print(k)之前将其用作玩具试用
使用更复杂的代码。我认为不检查p.empty()
的for
循环将无法工作。使用默认设置block=True,timeout=None
,p.get
将只等待项目可用。它不会给你一个None
到StopIteration
。这就是为什么循环永远不会结束。谢谢!我尝试了两种方法,第一种方法仍然不能自动终止,但第二种方法效果很好!谢谢我尝试了两种方法,第一种方法仍然不能自动终止,但第二种方法效果很好!