问题描述
如果长时间运行的单元发生故障,我想发送警报,但是我不想尝试/除外,因为那样的话,当我查看错误时,我将发送不必要的消息.有办法吗?
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?
所需的工作流程:
1)运行status=train()
单元格
2)在最初的15秒内没有看到错误
2) see no error in first 15 seconds
3)执行下一个单元格send_alert('done or error')
,无论单元格1的结果如何,该单元格都将执行.
3) execute next cell send_alert('done or error')
that will execute regardless of the outcome of cell 1.
4)去做别的事情
这里是一个单细胞解决方案,每次都会令人讨厌:
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')
推荐答案
这是一个解决方案,它具有很小但可扩展的自定义iPython魔术.
Here's one solution, with a pretty small but extensible custom iPython magic.
您可以将其保存在名为magics.py
的文件中,或具有pip可安装的软件包.我使用了可点子安装的东西:
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)
这里是使用此示例.请注意,%load_ext 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
.
这篇关于Jupyter:即使前一个单元出现故障也可以运行下一个单元的技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!