Jupyter魔术处理笔记本异常

Flo*_*emo 16 python jupyter jupyter-notebook

我的Jupyter笔记本中有一些长时间运行的实验.因为我不知道他们什么时候会完成,我会在笔记本的最后一个单元格中添加一个电子邮件功能,所以当笔记本完成后我会自动收到一封电子邮件.

但是当其中一个单元格中出现随机异常时,整个笔记本停止执行,我从未收到任何电子邮件.所以我想知道是否有一些魔法函数可以在异常/内核停止的情况下执行函数.

喜欢

def handle_exception(stacktrace):
    send_mail_to_myself(stacktrace)


%%in_case_of_notebook_exception handle_exception # <--- this is what I'm looking for
Run Code Online (Sandbox Code Playgroud)

另一种选择是将每个单元封装在try-catch中,对吧?但这太乏味了.

在此先感谢您的任何建议.

sho*_*w0k 17

这样的魔法命令不存在,但你可以自己编写.

from IPython.core.magic import register_cell_magic

@register_cell_magic
def handle(line, cell):
    try:
        exec(cell)
    except Exception as e:
        send_mail_to_myself(e)
        raise # if you want the full trace-back in the notebook
Run Code Online (Sandbox Code Playgroud)

无法自动为整个笔记本加载magic命令,您必须在需要此功能的每个单元格中添加该命令.

%%handle

some_code()
raise ValueError('this exception will be caught by the magic command')
Run Code Online (Sandbox Code Playgroud)


Flo*_*emo 12

@ 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)
Run Code Online (Sandbox Code Playgroud)

因此,这可以放在任何笔记本顶部的单个单元格中,因此如果出现问题,它将进行邮件发送.

自我/ TODO注意事项:将此片段变成一个小python模块,可以导入到笔记本中并通过魔术激活.

但要小心.该文档包含对此set_custom_exc方法的警告:"警告:通过将自己的异常处理程序放入IPython的主执行循环中,您可以很好地发生令人讨厌的崩溃.只有在您真正知道自己在做什么时才能使用此工具. "

  • 我重复使用了你漂亮的答案来添加声音&gt; /sf/ask/4282383031/ 61176901 (2认同)

d_j*_*d_j 5

从 notebook 5.1 开始,您可以使用新标签:raises-exception 这将表明特定单元格中的异常是预期的,并且 jupyter 不会停止执行。

(为了设置标签,您必须从主菜单中选择:查看 -> 单元格工具栏 -> 标签)