我有一个带有循环的python脚本,每次经常崩溃并有各种异常,需要重新启动.有没有办法在发生这种情况时运行一个动作,以便我可以收到通知?
您可以通过为sys.excepthook处理程序分配自定义函数来安装异常挂钩.只要存在未处理的异常(因此退出解释器的异常),就会调用该函数.
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
Run Code Online (Sandbox Code Playgroud)
只要sendmail您的系统上有工作命令,此异常挂钩会在程序退出时通过电子邮件向您发送回溯.