为什么我不能从多处理队列中捕获Queue.Empty异常? [英] Why can I not catch a Queue.Empty exception from a multiprocessing Queue?
问题描述
我正在尝试捕获在multiprocessing.Queue为空时引发的Queue.Empty异常。以下操作不起作用:
I'm trying to catch a Queue.Empty exception that is raised if a multiprocessing.Queue is empty. The following does not work:
import multiprocessing
f = multiprocessing.Queue()
try:
f.get(True,0.1)
except Queue.Empty:
print 'foo'
这给我一个名称错误:NameError:未定义名称'Queue'
This gives me a name error: NameError: name 'Queue' is not defined
用multiprocessing.Queue.Empty替换Queue.Empty并没有帮助要么。在这种情况下,它给我一个 AttributeError:'函数'对象没有属性'Empty'的异常。
replacing Queue.Empty with multiprocessing.Queue.Empty does not help either. In this case it gives me a "AttributeError: 'function' object has no attribute 'Empty'" exception.
推荐答案
您要查找的code> Empty 异常不能直接在 multiprocessing
模块中使用,因为 multiprocessing
从 Queue
模块(在Python 3中重命名为 queue
)中借用它。要使代码正常工作,只需在顶部执行导入队列
:
The Empty
exception you're looking for isn't available directly in the multiprocessing
module, because multiprocessing
borrows it from the Queue
module (renamed queue
in Python 3). To make your code work, just do an import Queue
at the top:
尝试以下操作:
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'
这篇关于为什么我不能从多处理队列中捕获Queue.Empty异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!