我的程序在遇到错误时会发送电子邮件。有没有办法处理这个程序的崩溃并用这个程序发送关于它的电子邮件?
问问题
570 次
1 回答
1
您正在寻找sys.excepthook
,这里是一个例子:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import cStringIO, traceback
from PyQt4 import QtGui, QtCore
errorNotice = """
An unhandled exception occurred. Details will be reported
via an automatic email.
"""
class MyMessageBox(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(MyMessageBox, self).__init__(*args, **kwargs)
self.tracebackInfoStream = cStringIO.StringIO()
self.setIcon(QtGui.QMessageBox.Critical)
self.finished.connect(self.on_finished)
def getTraceback(self, exceptionTraceback):
traceback.print_tb(
exceptionTraceback,
None,
self.tracebackInfoStream
)
self.tracebackInfoStream.seek(0)
return self.tracebackInfoStream.read()
def exceptHook(self, exceptionType, exceptionValue, exceptionTraceback):
tracebackInfo = self.getTraceback(exceptionTraceback)
self.setDetailedText(tracebackInfo)
self.setText(errorNotice)
self.exec_()
@QtCore.pyqtSlot()
def on_finished(self):
QtGui.QApplication.quit()
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonError = QtGui.QPushButton(self)
self.pushButtonError.setText("Raise an Error!")
self.pushButtonError.clicked.connect(self.on_pushButtonError_clicked)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.pushButtonError)
@QtCore.pyqtSlot()
def on_pushButtonError_clicked(self):
raise UserWarning("This is an error")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
myMessageBox = MyMessageBox()
sys.excepthook = myMessageBox.exceptHook
main = MyWindow()
main.show()
sys.exit(app.exec_())
于 2013-03-23T18:45:05.303 回答