10

Any trick to play a sound whenever a Jupyter notebook cell throws an error?

I checked this question, and I am currently using cellbell like this:

import cellbell

# line magic
%ding my_long_function()

but I don't know to make it run whenever one of my cells throws an error (except from wrapping every cell in try/catch clauses).

I guess what I would need is something like an "error-hook", similar to a savehook...

Community
  • 1
  • 1
Renaud
  • 16,073
  • 6
  • 81
  • 79

1 Answers1

10

Without cellbell (more generic answer)

Define a function in your notebook. **Note: Audio must be passed to display

from IPython.display import Audio, display

def play_sound(self, etype, value, tb, tb_offset=None):
    self.showtraceback((etype, value, tb), tb_offset=tb_offset)
    display(Audio(url='http://www.wav-sounds.com/movie/austinpowers.wav', autoplay=True))

set a custom exception handler, you can list exception types in the tuple.

get_ipython().set_custom_exc((ZeroDivisionError,), play_sound)

test it:

1/0

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-21-05c9758a9c21> in <module>()
----> 1 1/0

ZeroDivisionError: division by zero

With cellbell: The difference is using the %ding magic.

import cellbell

def play_sound(self, etype, value, tb, tb_offset=None):
    %ding
    self.showtraceback((etype, value, tb), tb_offset=tb_offset)
    print('ding worked!')

reset the custom exeception, note you can use Exception to play a sound on any error:

get_ipython().set_custom_exc((Exception,), play_sound)

test:

1/0

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-4-05c9758a9c21> in <module>()
----> 1 1/0

ZeroDivisionError: division by zero

ding worked!

tested on jupyter notebook 4.2.3

Kevin
  • 7,960
  • 5
  • 36
  • 57