2015-04-02 87 views
-1

我想从Python脚本中的控制台中出现的所有引发的异常发送一封电子邮件。这样做的一个例子是,如果我正在使用的json-web服务关闭,并将错误消息记录到我的控制台;那么除了控制台中记录的任何其他错误之外,我还想发送该消息。从Python中引发的异常发送电子邮件

在最底层;这是我会遇到的一个例子。我想电子邮件脚本中的所有相关联的错误,如果它失败,或返回exit code 1

import json 
import jsonpickle 
import requests 
import time 

f2 = open('C:\Users\Administrator\Desktop\DetailView.json', 'r') 
data2 = jsonpickle.encode(jsonpickle.decode(f2.read())) 
url2 = "HTTPERROR or ValueError prone URL that raises an exception" 
headers2 = {'Content-type': 'text/plain', 'Accept': '/'} 
r2 = requests.post(url2, data=data2, headers=headers2) 
decoded2 = json.loads(r2.text) 
Start = datetime.datetime.now() 

ValueError: No JSON object could be decoded

+2

适合你。你的问题是什么?请注意,堆栈溢出不是代码写入服务。 – MattDMo 2015-04-02 20:34:19

+0

可能的重复的[Python - 发送电子邮件时引发异常?](http://stackoverflow.com/questions/6182693/python-send-email-when-exception-is-raised) – 2015-04-02 20:50:43

回答

0

您想要使用的日志模块中提供的SMTP Handler。你可以在你关心的代码周围试一试,除非有任何异常,否则记录器将发送一封电子邮件。

例如:

try: 
    {my code} 
except Exception as e: 
    logger.error("My code threw an error", exc_info=True) 
    {handle exception} 

而且你必须在SMTP处理程序添加到您的日志记录配置:

[handler_smtpHandler] 
class=logging.handlers.SMTPHandler 
level=WARN 
formatter=simpleFormatter 
args=('localhost', '[email protected]', ['[email protected]'], "ERROR SUBJECT")