如何使用for循环而不是while循环遍历Python Queue.Queue?

问题描述 投票:22回答:3

通常我们这样编码:

while True:
    job = queue.get()
    ...

但它是否也可以做以下事情:

for job in queue.get():
    #do stuff to job

我想要这样做的真正原因是因为我想使用python-progressbar的自动检测maxval。他们像for this in progressbar(that):那样做

python
3个回答
37
投票

你可以使用iter与callable。 (你应该传递两个参数,一个用于可调用,另一个用于sentinel值)

for job in iter(queue.get, None): # Replace `None` as you need.
    # do stuff with job

注意当没有元素保留且没有放置标记值时,这将阻止。此外,像while-get循环和正常的for循环不同容器,它将从队列中删除项目。

更新:None是常见值,所以这里是一个具有更具体的标记值的示例:

sentinel = object()
for job in iter(queue.get, sentinel):
    # do stuff with job

8
投票

对于那种队列实际上我通常不会使用queue.empty()的这个检查,因为我总是在线程上下文中使用它,因此无法知道另一个线程是否会在几毫秒内放置一些东西(因此检查无论如何都是无用的)。我从不检查队列是否为空。我宁愿使用标记生产者结尾的sentinel值。

所以使用iter(queue.get, Sentinel)更像是我喜欢的。

如果您知道没有其他线程将项目放入队列中,并且只想将其从当前包含的所有项目中排除,那么您可以使用这样的:

class Drainer(object):
  def __init__(self, q):
    self.q = q
  def __iter__(self):
    while True:
      try:
        yield self.q.get_nowait()
      except queue.Empty:  # on python 2 use Queue.Empty
        break

for item in Drainer(q):
  print(item)

要么

def drain(q):
  while True:
    try:
      yield q.get_nowait()
    except queue.Empty:  # on python 2 use Queue.Empty
      break

for item in drain(q):
  print(item)

5
投票

我的第一个是iter函数,但是内置队列模块没有返回一个sentinel,所以一个很好的选择可能是定义你自己的包装类:

import Queue

class IterableQueue():
    def __init__(self,source_queue):
            self.source_queue = source_queue
    def __iter__(self):
        while True:
            try:
               yield self.source_queue.get_nowait()
            except Queue.Empty:
               return

这个迭代器包装队列并产生,直到队列为空,然后返回,所以现在你可以这样做:

q = Queue.Queue()
q.put(1)
q.put(2)
q.put(3)

for n in IterableQueue(q):
    print(n)

输出:

1
2
3

如果有人知道使用内置函数更好的话,这个方法有点冗长会很有趣。

© www.soinside.com 2019 - 2024. All rights reserved.