问题
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