Why can I not catch a Queue.Empty exception from a multiprocessing Queue?
The Empty
exception you're looking for isn't available directly in the multiprocessing
module, because multiprocessing
borrows it from the queue
module (which used to be named Queue
in Python 2). To make your code work, just do an import queue
at the top:
Try this:
import multiprocessing
import queue # or Queue in Python 2
f = multiprocessing.Queue()
try:
f.get(True,0.1)
except queue.Empty: # queue here refers to the module, not a class
print('foo')
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...