Jupyter:即使前一个单元格失败,也会欺骗 运行 下一个单元格

Jupyter: trick to run next cell even if previous cell fails

我想在长 运行ning 单元出现故障时发送警报,但我不想 try/except 因为那样我会在查看错误时发送不必要的消息。有办法吗?

所需的工作流程:

1) 运行 status=train() 单元格

2) 在前 15 秒内没有发现任何错误

3) 执行下一个单元格 send_alert('done or error'),无论单元格 1 的结果如何都会执行。

4) 去做点别的事情

这是一个单细胞解决方案,每次编码都很烦人:

try:
    start = time.time()
    train(...)
except Exception as e:
    pass
end = time.time()
if end - start > 60: send_alert('done')

这是一个解决方案,具有非常小但可扩展的自定义 iPython 魔法。

您可以将其保存在某个名为 magics.py 的文件中,或者拥有一个可安装 pip 的软件包。我使用了一些可安装 pip 的东西:

.
├── magics
│   ├── __init__.py
│   └── executor.py
└── setup.py
# magics/executor.py

import time
from IPython.core.magic import Magics, magics_class, cell_magic

@magics_class
class Exceptor(Magics):

    @cell_magic
    def exceptor(self, line, cell):
        timeout = 2
        try:
            start = time.time()
            self.shell.ex(cell)
        except:
            if time.time() - start > timeout:
                print("Slow fail!")
        else:
            if time.time() - start > timeout:
                print("done")
# magics/__init__.py

from .exceptor import Exceptor

def load_ipython_extension(ipython):
    ipython.register_magics(Exceptor)

这是一个使用它的例子。请注意 %load_ext magics 获取包的名称,然后为您提供名为 %exceptor.

的单元魔法