Guest User

Untitled

a guest
Jan 16th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. def handle_exception(stacktrace):
  2. send_mail_to_myself(stacktrace)
  3.  
  4.  
  5. %%in_case_of_notebook_exception handle_exception # <--- this is what I'm looking for
  6.  
  7. from IPython.core.magic import register_cell_magic
  8.  
  9. @register_cell_magic
  10. def handle(line, cell):
  11. try:
  12. exec(cell)
  13. except Exception as e:
  14. send_mail_to_myself(e)
  15. # Reraise to have the full traceback in the notebook
  16. raise
  17.  
  18. %%handle
  19.  
  20. some_code()
  21. raise ValueError('this exception will be caught by the magic command')
  22.  
  23. from IPython.core.ultratb import AutoFormattedTB
  24.  
  25. # initialize the formatter for making the tracebacks into strings
  26. itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
  27.  
  28. # this function will be called on exceptions in any cell
  29. def custom_exc(shell, etype, evalue, tb, tb_offset=None):
  30.  
  31. # still show the error within the notebook, don't just swallow it
  32. shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
  33.  
  34. # grab the traceback and make it into a list of strings
  35. stb = itb.structured_traceback(etype, evalue, tb)
  36. sstb = itb.stb2text(stb)
  37.  
  38. print (sstb) # <--- this is the variable with the traceback string
  39. print ("sending mail")
  40. send_mail_to_myself(sstb)
  41.  
  42. # this registers a custom exception handler for the whole current notebook
  43. get_ipython().set_custom_exc((Exception,), custom_exc)
Add Comment
Please, Sign In to add comment