Jonathan
Jonathan

Reputation: 11321

Is there a way to have a python program run an action when it's about to crash?

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?

Upvotes: 3

Views: 2580

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1123940

You could install an exception hook, by assigning a custom function to the sys.excepthook handler. 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"] = "[email protected]"
    msg["To"] = "[email protected]"
    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.

Upvotes: 10

hawer183
hawer183

Reputation: 109

You should try like this:

while True:
        try:
            x = int(raw_input("Please enter a number: "))
            break
        except ValueError:
            print "Oops!  That was no valid number.  Try again..."

Upvotes: 0

Maxime Lorant
Maxime Lorant

Reputation: 36181

You can surrond your whole program with a try/except block, which is not very beautiful I find. Another way is to run your python script in a .sh file and execute this:

#!/bin/bash

while true
do
    python your_script.py
    if $? != 0 then
        sendmail "blabla" "see the doc" "for arguments"
    fi
done

This will execute the Python script and when it stops, it'll send you a mail and restarted it (since it's an infinite loop). The mail is sent only if there's an error in the Python program and the exit code is different of 0. To be more efficient, you could get the stdout, and put it in the mail to know what fails and how resolve this.

Upvotes: 0

Related Questions