22

For some reason I can't access the Queue.Empty exception - what am I doing wrong here?

from multiprocessing import Process, Queue

# ...

try:
    action = action_queue.get(False)
    print "Action: " + action
except Queue.Empty:
    pass

The stack trace:

Traceback (most recent call last):  
File "C:\Program Files\Python27\lib\multiprocessing\process.py", line 258,
  in _bootstrap
  self.run()
File "C:\Program Files\Python27\lib\multiprocessing\process.py", line 114,
  in run
  self._target(*self._args, **self._kwargs)
File "D:\Development\populate.py", line 39, in permutate
  except Queue.Empty: AttributeError: 'function' object has no attribute 'Empty'

2 Answers 2

28

The Queue.Empty exception is in the Queue module, not in the multiprocessing.queues.Queue class. The multiprocessing module actually uses the Queue (module) Empty exception class:

from multiprocessing import Queue
from Queue import Empty
q = Queue()
try:
    q.get( False )
except Empty:
    print "Queue was empty"

If you want to be very explicit and verbose, you can do this:

import multiprocessing
import Queue
q = multiprocessing.Queue()
try:
    q.get( False )
except Queue.Empty:
    print "Queue was empty"

Favoring the former approach is probably a better idea because there is only one Queue object to worry about and you don't have to wonder if you are working with the class or the module as in my second example.

Sign up to request clarification or add additional context in comments.

5 Comments

Ah I see now, I thought importing Queue imported the module, rather than the class. Thanks!
it's even more interesting -- importing from multiprocessing import Queue imports the Queue function from the __init__.py in multiprocessing which returns the Queue class from the multiprocessing.queues sub module. Duck typing and namespaces make for interesting programming!
Just a note, this answer has a typo in "execpt" for the copy/paste coders, and the import statement should be lowercase Queue.
from multiprocessing import Queue \ from Queue import Empty gives me ModuleNotFoundError: No module named 'Queue' :(
OK. for those with similar issue see stackoverflow.com/questions/33432426/… tldr it has to be "Joinable Queue" in py3
1

In Python 3, this is one way to do it. Note the lowercase 'queue':

from multiprocessing import Queue
from queue import Empty as QueueEmpty
q = Queue()
try:
    q.get(False)
except QueueEmpty:
    print "Queue was empty"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.