Issue
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')
Solution
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/
Answered By - Ludo Schmidt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.