@show0k 对我的问题给出了正确答案(关于魔术方法)。非常感谢! :)
这个答案激发了我深入挖掘的灵感,我发现了一个 IPython 方法,它允许您为整个笔记本定义一个自定义异常处理程序。
我让它像这样工作:
from IPython.core.ultratb import AutoFormattedTB
# initialize the formatter for making the tracebacks into strings
itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
# this function will be called on exceptions in any cell
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
# still show the error within the notebook, don't just swallow it
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
# grab the traceback and make it into a list of strings
stb = itb.structured_traceback(etype, evalue, tb)
sstb = itb.stb2text(stb)
print (sstb) # <--- this is the variable with the traceback string
print ("sending mail")
send_mail_to_myself(sstb)
# this registers a custom exception handler for the whole current notebook
get_ipython().set_custom_exc((Exception,), custom_exc)
因此,这可以放入任何笔记本顶部的单个单元格中,因此它会在出现问题时进行邮寄。
自我/TODO注意事项:将这个sn-p变成一个小python模块,可以导入笔记本并通过line magic激活。
不过要小心。该文档包含此 set_custom_exc 方法的警告:“警告:通过将您自己的异常处理程序放入 IPython 的主执行循环中,您很有可能会发生严重的崩溃。只有在您真的知道自己的情况下才应该使用此工具正在做。”