Python 线程和父线程中的异常捕获
如何在Python线程中很好地捕获异常 如果您有一个线程化的python应用程序,则sys.excepthook不会捕获子系统中的错误 当子级引发异常时,父级将继续运行,不会出现任何问题,因此调试有点困难Python 线程和父线程中的异常捕获,python,Python,如何在Python线程中很好地捕获异常 如果您有一个线程化的python应用程序,则sys.excepthook不会捕获子系统中的错误 当子级引发异常时,父级将继续运行,不会出现任何问题,因此调试有点困难 import os import sys import signal import string import threading # capture Exceptions def except_catch(type, value, track, thread): import tra
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()