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...
Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.
Jupyter fails to start If you're using a menu shortcut or Anaconda launcher to start it, try opening a terminal or command prompt and running the command jupyter notebook . If it can't find jupyter , you may need to configure your PATH environment variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With