Reputation: 3331
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.
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 ?
Upvotes: 2
Views: 1350
Reputation: 169268
Keyboard interrupts (ctrl+c) manifest as KeyboardInterrupt
exceptions, so
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!).
Upvotes: 5