如何很好地捕获 Python 线程中的异常?
如果你有一个线程化的 python 应用程序sys.excepthook不会捕获子级的错误。
当孩子引发异常时,父母将继续运行而不会出现任何问题,从而使调试变得有点困难。
如何很好地捕获 Python 线程中的异常?
如果你有一个线程化的 python 应用程序sys.excepthook不会捕获子级的错误。
当孩子引发异常时,父母将继续运行而不会出现任何问题,从而使调试变得有点困难。
import os
import sys
import signal
import string
import threading
# capture Exceptions
def except_catch(type, value, track, thread):
  import traceback
  rawreport = traceback.format_exception(type, value, track)
  report = "\n" . join(rawreport)
  errorlog = open("errors.log", "a")
  if thread != "":
    errorlog.write("Exception in thread: " + thread + "\n\n")
  errorlog.write(("%s\n" + "-" * 30 + "\n\n") % report)
  errorlog.close()
sys.excepthook = except_catch
# capture KeyboardInterrupt
def interrupt_catch(signal, frame):
  print ""
  os._exit(1)
signal.signal(signal.SIGINT, interrupt_catch)
# all your threaded code here
def whatever_threaded_function():
  try:
    a = 1 / 0
  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    except_catch(exc_type.__name__, exc_value, exc_traceback, threading.current_thread().name)
threading.Thread(target=whatever_threaded_function).start()