Exception Capture In Threads And Parent
How do you nicely capture exceptions in Python threads? If you have a threaded python app sys.excepthook does not capture errors in children. When a child raises an exception the p
Solution 1:
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()
Post a Comment for "Exception Capture In Threads And Parent"