在python的多处理中检查空队列

Raf*_*ini 7 python queue multiprocessing

我有一个程序使用python的包多处理和队列.我的一个函数有这个结构:

from multiprocessing import Process, Queue
def foo(queue):
   while True:
       try:
           a = queue.get(block = False)
           doAndPrintStuff(a)
       except:
           print "the end"
           break

   if __name__ == "__main__"
     nthreads = 4
     queue = Queue.Queue()
     # put stuff in the queue here 
     for stuff in moreStuff:
         queue.put(stuff)
     procs = [Process(target = foo, args = (queue,)) for i in xrange(nthreads)]
     for p in procs:
       p.start()
     for p in procs:
       p.join()
Run Code Online (Sandbox Code Playgroud)

我的想法是,当我尝试从队列中提取并且它是空的时,它将引发异常并终止循环.所以我有两个问题:

1)这是一个安全的成语吗?有没有更好的方法来做到这一点?

2)我试图找到当我尝试.get()从空队列中引发的确切异常.目前我的程序正在捕获所有异常,当错误发生在其他地方并且我只收到"结束"消息时会很糟糕.

我试过了:

  import Queue
  queue = Queue.Queue()
  [queue.put(x) for x in xrange(10)]
  try: 
       print queue.get(block = False)
  except Queue.Empty:
       print "end"
       break
Run Code Online (Sandbox Code Playgroud)

但我得到了错误,好像我没有抓住异常.捕获的正确例外是什么?

Ste*_*ven 15

例外应该是Queue.Empty.但你确定你得到了同样的错误吗?在您的第二个示例中,您还将队列本身从切换multiprocessing.QueueQueue.Queue,我认为这可能是问题所在.

它可能看起来很奇怪,但你必须使用multiprocessing.Queue该类,但使用Queue.Empty异常(你必须自己从Queue模块导入)