为什么我不能从多处理队列中捕获Queue.Empty异常?

Ale*_*der 20 python exception-handling python-2.7

我正在尝试捕获如果multiprocessing.Queue为空时引发的Queue.Empty异常.以下不起作用:

import multiprocessing
f = multiprocessing.Queue()
try:
      f.get(True,0.1)
except Queue.Empty:
      print 'foo'
Run Code Online (Sandbox Code Playgroud)

这给了我一个名称错误:NameError:名称'Queue'未定义

用multiprocessing.Queue.Empty替换Queue.Empty也没有帮助.在这种情况下,它给了我一个"AttributeError:'function'对象没有属性'Empty'"异常.

Blc*_*ght 35

Empty您正在寻找的异常不能直接在multiprocessing模块中使用,因为multiprocessingQueue模块借用它(queue在Python 3中重命名).要使代码正常工作,只需import Queue在顶部执行:

试试这个:

import multiprocessing
import Queue # or queue in Python 3

f = multiprocessing.Queue()
try:
    f.get(True,0.1)
except Queue.Empty: # Queue here refers to the  module, not a class
    print 'foo'
Run Code Online (Sandbox Code Playgroud)

  • [`multiprocessing`应该(并且确实)使用`isinstance(exception,Queue.Empty)`](http://ideone.com/iHpNoJ)(Queue是一个模块),因为多处理模拟经常与Queue.Queue一起使用的线程api和例外是api的一部分. (2认同)
  • 原来如此。`multiprocessing.queues.Empty` 是 `Queue.Empty`(只是为了使用 `multiprocessing.queues.Queue` 而导入)。我会更新答案。 (2认同)

gga*_*epy 6

Blckknght在2012年的回答仍然是正确的,但是使用Python 3.7.1时,我发现必须使用queue.Empty作为要捕获的异常的名称(请注意,“ queue”中的小写字母“ q”)。

因此,回顾一下:

import queue

# Create a queue
queuevarname = queue.Queue(5) # size of queue is unimportant

while some_condition_is_true:
    try:
        # attempt to read queue in a way that the exception could be thrown
        queuedObject = queuevarname.get(False)

        ...
    except queue.Empty:
        # Do whatever you want here, e.g. pass so
        # your loop can continue, or exit the program, or...
Run Code Online (Sandbox Code Playgroud)