当Jupyter笔记本电脑发生故障时播放声音

问题描述 投票:3回答:1

每当Jupyter笔记本电脑发出错误时播放声音的任何技巧?

我检查了this question,我目前正在使用这样的cellbell

import cellbell

# line magic
%ding my_long_function()

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

我想我需要的东西就像一个“错误勾”,类似于savehook ......

ipython ipython-notebook jupyter-notebook
1个回答
4
投票

没有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笔记本4.2.3上测试

© www.soinside.com 2019 - 2024. All rights reserved.