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
模块中使用,因为multiprocessing
从Queue
模块借用它(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)
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)
归档时间: |
|
查看次数: |
19348 次 |
最近记录: |