python - Jupyter / Colab:在任何单元格中播放任何错误的声音+在完成长时间运行的单元格后播放声音
问题描述
有时会发生错误,但我没有注意到,因为我可能同时运行多个单元。
我希望错误播放声音。
许多人希望长时间运行的单元格在完成后播放声音。
解决方案
a) 创建一个对错误发出哔哔声的全局异常处理程序
b)创建一个简单的函数,放置在长时间运行的单元格的末尾(链接上的一些其他方法)
您可以将声音更改为您喜欢的任何内容。
注意:异常处理程序和 beep_completed() 内部的声音非常不同,并且是有原因的。第一个简短且不烦人,第二个冗长且令人愉快(如果您远离计算机,那么您可以清楚地听到任务已完成)。在任何情况下,您都可以更换它们。
注意:有一条线仅适用于 Colab。如果您可以为 Jupyter 提供一个,我会很乐意更新答案。
# This line is specific for Colab (please provide alternative for Jupyter)
from google.colab import output
from IPython.core.ultratb import AutoFormattedTB
# Catch any Exception, play error sound and re-raise the Exception
#-------------------------------------------------
# initialize the formatter for making the tracebacks into strings
itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
# this function will be called on exceptions in any cell
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
# still show the error within the notebook, don't just swallow it
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
# Play an audio beep. Any audio URL will do.
output.eval_js('new Audio("http://soundbible.com/grab.php?id=419&type=wav").play()')
# # grab the traceback and make it into a list of strings
# stb = itb.structured_traceback(etype, evalue, tb)
# sstb = itb.stb2text(stb)
# print (sstb) # <--- this is the variable with the traceback string
# print ("sending mail")
# send_mail_to_myself(sstb)
# this registers a custom exception handler for the whole current notebook
get_ipython().set_custom_exc((Exception,), custom_exc)
#------------------------------------------
# Function to play a sound (to put at the end of a long job)
def beep_completed():
#url_sound="http://soundbible.com/grab.php?id=1795&type=mp3";
output.eval_js('new Audio("http://soundbible.com/grab.php?id=1795&type=mp3").play()')
# Just play it with
beep_completed()
推荐阅读
- machine-learning - 如何确定深度学习中嵌入、LSTM、层中的单元数量
- three.js - 使用一个着色器但有多个纹理的几何实例化
- swift - AVPlayerLayer/CALayer removeFromSuperlayer() 泄漏
- php - 有没有办法更新单个用户完成的不同交易的状态?
- php - 拉拉维尔。有没有办法将 API 资源作为参数传递?
- azure - Azure 函数的 Host.json 中的 MaxBatchSize 不起作用
- angular - 无法使用“return of(false)”返回布尔值
- javascript - 访问通过 jQuery $.post 发送的数据时遇到问题
- ffmpeg - 如何防止 ffmpeg JPG->MP4 添加假帧?
- arrays - 在python中重新标记数组元素或使元素连续的快速方法