Why can I not catch a Queue.Empty exception from a multiprocessing Queue?

风流意气都作罢 提交于 2019-12-09 08:18:03

问题


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'

This gives me a name error: 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.


回答1:


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:

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'



回答2:


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'.)

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...


来源:https://stackoverflow.com/questions/13941562/why-can-i-not-catch-a-queue-empty-exception-from-a-multiprocessing-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!