简体   繁体   中英

Exception handling while iterating over Python queues

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM