Is there a way to have a python program run an action when it's about to crash?
Question: I have a python script with a loop that crashes every so often with various
exceptions, and needs to be restarted. Is there a way to run an action when
this happens, so that I can be notified?


Answer: You could install an exception hook, by assigning a custom function to the
[`sys.excepthook`
handler](http://docs.python.org/2/library/sys.html#sys.excepthook). The
function is called whenever there is a _unhandled_ exception (so one that
exits the interpreter).

    
    
    import sys
    
    def myexcepthook(type, value, tb):
        import traceback
        from email.mime.text import MIMEText
        from subprocess import Popen, PIPE
        tbtext = ''.join(traceback.format_exception(type, value, tb))
        msg = MIMEText("There was a problem with your program:\n\n" + tbtext)
        msg["From"] = "me@example.com"
        msg["To"] = "you@example.com"
        msg["Subject"] = "Program exited with a traceback."
        p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
        p.communicate(msg.as_string())
    
    sys.excepthook = myexcepthook
    

This exception hook emails you the traceback whenever the program exits,
provided you have a working `sendmail` command on your system.

