Python 捕获线程中的异常

import sys
from threading import Thread


def install_thread_excepthook():

    init_original = Thread.__init__

    def init(self, *args, **kwargs):
        init_original(self, *args, **kwargs)
        run_original = self.run

        def run_with_except_hook(*a, **kw):
            try:
                run_original(*a, **kw)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                sys.excepthook(*sys.exc_info())

        self.run = run_with_except_hook

    Thread.__init__ = init