Jupyter Magic处理笔记本异常 [英] Jupyter magic to handle notebook exceptions

查看:79
本文介绍了Jupyter Magic处理笔记本异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.

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

But when there is a random exception in one of the cells, the whole notebook stops executing and I never get any email. So I'm wondering if there is some magic function that could execute a function in case of an exception / kernel stop.

喜欢

def handle_exception(stacktrace):
    send_mail_to_myself(stacktrace)


%%in_case_of_notebook_exception handle_exception # <--- this is what I'm looking for

另一个选择是将每个单元格封装在try-catch中,对吗?但这太麻烦了.

The other option would be to encapsulate every cell in try-catch, right? But that's soooo tedious.

提前感谢您的任何建议.

Thanks in advance for any suggestions.

推荐答案

这种魔术命令不存在,但是您可以自己编写.

Such a magic command does not exist, but you can write it yourself.

from IPython.core.magic import register_cell_magic

@register_cell_magic('handle')
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

不可能为整个笔记本自动加载magic命令,您必须将其添加到需要此功能的每个单元中.

It is not possible to load the magic command for the entire notebook automatically, you have to add it at each cell where you need this feature.

%%handle

some_code()
raise ValueError('this exception will be caught by the magic command')

这篇关于Jupyter Magic处理笔记本异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆