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

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

问题描述

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

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

不可能自动加载整个笔记本的魔法命令,您必须在需要此功能的每个单元格中添加它.

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 处理笔记本异常的魔法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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