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

拟墨画扇 提交于 2021-02-10 16:50:18

问题


I want to send alerts if a long running cell fails, but I don't want to try/except because then I will send needless messages when I am looking at the error. Is there a way to do this?

Desired workflow:

1) run status=train() cell

2) see no error in first 15 seconds

3) execute next cell send_alert('done or error') that will execute regardless of the outcome of cell 1.

4) Go do something else

Here is a one cell solution that is annoying to code every time:

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

回答1:


Here's one solution, with a pretty small but extensible custom iPython magic.

You can keep it in a file named magics.py somewhere, or have a pip-installable package. I used something pip-installable:

.
├── 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)

Here is an example of using this. Notice that %load_ext magics takes the name of the package, and then gives you the cell magic named %exceptor.



来源:https://stackoverflow.com/questions/57364510/jupyter-trick-to-run-next-cell-even-if-previous-cell-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!