21

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'
Ross
  • 46,186
  • 39
  • 120
  • 173

2 Answers2

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.

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
underrun
  • 6,713
  • 2
  • 41
  • 53
  • Ah I see now, I thought importing Queue imported the module, rather than the class. Thanks! – Ross Jun 27 '11 at 11:25
  • 2
    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! – underrun Jun 27 '11 at 13:02
  • 1
    Just a note, this answer has a typo in "execpt" for the copy/paste coders, and the import statement should be lowercase Queue. – Source Matters Nov 02 '18 at 00:09
  • 2
    `from multiprocessing import Queue \ from Queue import Empty` gives me `ModuleNotFoundError: No module named 'Queue'` :( – Rotkiv Mar 24 '19 at 02:02
  • OK. for those with similar issue see https://stackoverflow.com/questions/33432426/importerror-no-module-named-queue tldr it has to be "Joinable Queue" in py3 – Rotkiv Mar 24 '19 at 02:05
0

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"
theRPGmaster
  • 107
  • 1
  • 6