如何告诉 python 在运行时出现异常以向代码作者发送电子邮件?
How to tell python when it gets exception at runtime to send email to the author of code?
我可以从 python 发送电子邮件,但现在我需要在异常时通过 python 编译器发送电子邮件。
更新:
我找到了解决方案。
except SystemExit as e:
# avoid email exception on exit
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
raise
# (Insert your cleanup code here.)
import linecache
import sys
import subprocess
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
s = 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
print s
print "Send email..."
subprocess.Popen(['python', 'mailsender_exception.py', s])
print "end."
您可以使用 try/except 块捕获异常
try:
do_something()
except SomeException:
send_email()
我可以从 python 发送电子邮件,但现在我需要在异常时通过 python 编译器发送电子邮件。
更新: 我找到了解决方案。
except SystemExit as e:
# avoid email exception on exit
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
raise
# (Insert your cleanup code here.)
import linecache
import sys
import subprocess
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
s = 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
print s
print "Send email..."
subprocess.Popen(['python', 'mailsender_exception.py', s])
print "end."
您可以使用 try/except 块捕获异常
try:
do_something()
except SomeException:
send_email()