vlemaistre
vlemaistre

Reputation: 3331

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.

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

Answers (1)

AKX
AKX

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

Related Questions