Answer a question

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.

Answers

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐