我想要一个异常,在出现时总是发送一封电子邮件。至于现在,我正计划将该代码放入 __init():
import sendmail
import configparser
def MailException(BaseException):
"""
sends mail when initiated
"""
def __init__(self, message, config=None):
# Call the base class constructor with the parameters it needs
BaseException.__init__(message)
if config is None:
config = configparser.RawConfigParser()
config.read('mail.ini')
config = config['email']
text = 'exception stack trace + message'
sendmail.sendMail(text=text, config=config['email'], title='Alert')
我明确希望在这里发送邮件,而不是在我创建的每个 except-block 中。因此我想知道如何获取堆栈跟踪,代码必须与 Python 2.7 兼容。
我唯一能找到的是traceback,但这显然只适用于except: 领域——或者有没有办法在Exception 类中实现它?还有其他想法吗?
请您参考如下方法:
首先,请注意(根据 the docs )您不应该继承 BaseException。
其次,您可以定义一个新的 sys.excepthook,而不是在异常本身中实现该逻辑。 (参见例如 Python Global Exception Handling ),然后您可以访问完整的回溯:
import sys
class MailException(Exception):
pass
def mailing_except_hook(exctype, value, traceback):
if exctype == MailException:
... # do your thing here
else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = mailing_except_hook
