2

I've got a bunch of queues stored in the global globqueue array. I now want to iterate over all these queues and get all the items inside of them.

I'm having a few problems with getting the items from the queue, though. I'm using .get_nowait(), which will throw an "Empty" exception if there is nothing in the queue. I thought I could catch it like this:

                    for index, item in enumerate(globqueue):
                        print index, item

                        iterme = 1

                        while iterme:
                            try:
                                getiterme = item.get_nowait()
                                print getiterme
                            except ValueError:
                                iterme = 0
                                continue

But I'm still getting this error, and the rest of the code won't continue:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "server.py", line 213, in run
    getiterme = item.get_nowait()
  File "/usr/lib/python2.6/Queue.py", line 190, in get_nowait
    return self.get(False)
  File "/usr/lib/python2.6/Queue.py", line 165, in get
    raise Empty
Empty

I know I could check the size of the queue first with .qsize(), but I also read that isn't always so accurate so.. better to ask for forgiveness than permission, right?

1 Answer 1

6

You are catching ValueError but the call raises Empty. Try changing your except handler to catch the Empty exception instead.

from _queue import Empty

if __name__ == '__main__':
    try:
        item = item.get_nowait()
        # do some work
    except Empty:
        pass # handle error
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, I didn't know the part behind 'except' was that important. Queue.Empty didn't work, though, but changing it to 'Exception' (which contains "all built-in, non-system-exiting exceptions") it did work. Thanks
@skerit: except Exception: (or even worse, except:) is very dangerous. It even catched NameError - i.e. silly typos and other errors you want to learn about will be silenced. How did the proper solution "not work"?
Oh, I'm sorry. I typed "queue", without a capital. But the error message then said AttributeError: Queue instance has no attribute 'Empty' which made me think I did write it with a capital. Indeed, Queue.Empty works as it should.
@ckerit: I mistyped it in an earlier version of my answer. Sorry about that.

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.