python 线程之间传递异常

搞了一个折中的办法,虽然效果不咋地,但总归可以抓到东西。

#coding:utf-8



import time

import threading

import Queue





rlock = threading.RLock()





class MThread(threading.Thread):

    

    def __init__(self, oputque, *args, **kd_args):

        super(MThread, self).__init__(*args, **kd_args)

        self.oputque = oputque



    def _run(self):

        n = self.getName().replace('-', '_')

        for i in range(5):

            time.sleep(1)

            with rlock:

                print n, i

        raise Exception("Bad thing")



    def run(self):

        try:

            self._run()

        except Exception, err:            

            self.oputque.put(err)





def main():

    q = Queue.Queue()

    t = MThread(q)



    t.start()

    t.join()

    try:

        er = q.get_nowait()

        with rlock:

            print str(er)

    except Queue.Empty:

        pass

    print "Done"





if __name__ == '__main__':

    main()

 

你可能感兴趣的:(python)