简体   繁体   English

如果内核中断则执行代码(Jupyter notebook 中的 Python)

[英]Execute code if kernel is interrupted (Python in Jupyter notebook)

I am running a function in a Jupyter notebook and I would like to know if it's possible to execute a bit of code if the user interrupts the kernel.我正在 Jupyter 笔记本中运行一个函数,我想知道如果用户中断内核是否可以执行一些代码。

For example if you have this function:例如,如果你有这个功能:

import time
def time_sleep():
    time.sleep(5)
    print('hello')

Can I add a print('cell terminated') that runs if the cell is interrputed ?如果单元格被中断,我可以添加一个运行的print('cell terminated')吗?

Keyboard interrupts (ctrl+c) manifest as KeyboardInterrupt exceptions, so键盘中断 (ctrl+c) 表现为KeyboardInterrupt异常,因此

try: 
    time.sleep(5)
    print('That was a nice nap.')
except KeyboardInterrupt:
    print('What a rude awakening!')

works if Jupyter sends a real interrupt signal to the kernel (and apparently it does!).如果 Jupyter 向内核发送一个真正的中断信号(显然它确实如此!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM