sickerin
sickerin

Reputation: 540

Interrupt a loop that has a Try-Catch Block in IPython

If I have a for loop with a try-catch block, and I interrupt the kernel, the loop will go to error block and simply proceed to the next iteration. I would like to stop the loop entirely, is there a way to do that? Currently, I'll have to kill the kernel if I want to stop the loop, which means loading up the models, etc again, which takes time.

Example: I would like to know if there's a way to interrupt the entire for loop rather than just one iteration if I made a typo.

import time
for i in range(100):
    try:
        time.sleep(5)
        print(i)
    except:
        print('err')

Upvotes: 2

Views: 1468

Answers (2)

Ludo Schmidt
Ludo Schmidt

Reputation: 1413

just catch your keyboard interrupt in your try/catch.

for i in range(100):
    try:
        time.sleep(5)
        print(i)

    except KeyboardInterrupt:
       print ('KeyboardInterrupt exception is caught')
       raise # if you want everithings to stop now
       #break # if you want only to go out of the loop
    else:
       print('unexpected err')

more info : https://www.delftstack.com/howto/python/keyboard-interrupt-python/

Upvotes: 2

Mureinik
Mureinik

Reputation: 312086

You can break out of the loop:

for i in range(100):
    try:
        time.sleep(5)
        print(i)
    except:
        print('err')
        break

Upvotes: 0

Related Questions