当 Jupyter notebook 电池出现故障时播放声音

play sound when Jupyter notebook cell fails

有什么技巧可以在 Jupyter notebook 单元格抛出错误时播放声音

我这样检查this question, and I am currently using cellbell

import cellbell

# line magic
%ding my_long_function()

但我不知道每当我的一个单元格抛出错误时就让它成为 运行(除了将每个单元格包装在 try/catch 子句中)。

我想我需要的是 "error-hook",类似于 savehook...

没有 cellbell(更通用的答案)

在笔记本中定义一个函数。 **注意:Audio必须传递给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))

设置自定义异常处理程序,可以在元组中列出异常类型。

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

测试一下:

1/0

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

ZeroDivisionError: division by zero

cellbell: 不同之处在于使用 %ding 魔法。

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!')

重置自定义异常,注意您可以使用 Exception 在出现任何错误时播放声音:

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

测试:

1/0

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

ZeroDivisionError: division by zero

ding worked!

在 jupyter notebook 4.2.3 上测试