Python 为什么我不能从多处理队列中捕获 Queue.Empty 异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13941562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can I not catch a Queue.Empty exception from a multiprocessing Queue?
提问by Alexander
I'm trying to catch a Queue.Empty exception that is raised if a multiprocessing.Queue is empty. The following does not work:
我正在尝试捕获如果 multiprocessing.Queue 为空时引发的 Queue.Empty 异常。以下不起作用:
import multiprocessing
f = multiprocessing.Queue()
try:
f.get(True,0.1)
except Queue.Empty:
print 'foo'
This gives me a name error: NameError: name 'Queue' is not defined
这给了我一个名称错误:NameError: name 'Queue' is not defined
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.
用 multiprocessing.Queue.Empty 替换 Queue.Empty 也无济于事。在这种情况下,它给了我一个“AttributeError:'function' object has no attribute 'Empty'”异常。
采纳答案by Blckknght
The Emptyexception you're looking for isn't available directly in the multiprocessingmodule, because multiprocessingborrows it from the Queuemodule (renamed queuein Python 3). To make your code work, just do an import Queueat the top:
Empty您要查找的异常不能直接在multiprocessing模块中使用,因为multiprocessing它是从Queue模块中借用的(queue在 Python 3 中重命名)。要使您的代码正常工作,只需import Queue在顶部执行以下操作:
Try this:
尝试这个:
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'
回答by ggariepy
Blckknght's answer from back in 2012 is still correct, however using Python 3.7.1 I discovered that you have to use queue.Empty as the name of the exception to catch (Note the lowercase 'q' in 'queue'.)
Blckknght 在 2012 年的回答仍然是正确的,但是使用 Python 3.7.1 我发现您必须使用 queue.Empty 作为要捕获的异常的名称(注意“队列”中的小写“q”。)
So, to recap:
所以,回顾一下:
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...

