Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def handle_exception(stacktrace):
- send_mail_to_myself(stacktrace)
- %%in_case_of_notebook_exception handle_exception # <--- this is what I'm looking for
- from IPython.core.magic import register_cell_magic
- @register_cell_magic
- def handle(line, cell):
- try:
- exec(cell)
- except Exception as e:
- send_mail_to_myself(e)
- # Reraise to have the full traceback in the notebook
- raise
- %%handle
- some_code()
- raise ValueError('this exception will be caught by the magic command')
- from IPython.core.ultratb import AutoFormattedTB
- # initialize the formatter for making the tracebacks into strings
- itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
- # this function will be called on exceptions in any cell
- def custom_exc(shell, etype, evalue, tb, tb_offset=None):
- # still show the error within the notebook, don't just swallow it
- shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
- # grab the traceback and make it into a list of strings
- stb = itb.structured_traceback(etype, evalue, tb)
- sstb = itb.stb2text(stb)
- print (sstb) # <--- this is the variable with the traceback string
- print ("sending mail")
- send_mail_to_myself(sstb)
- # this registers a custom exception handler for the whole current notebook
- get_ipython().set_custom_exc((Exception,), custom_exc)
Add Comment
Please, Sign In to add comment