中断在 IPython 中具有 Try-Catch 块的循环

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

如果我有一个带有 try-catch 块的 for 循环,并且我中断了内核,该循环将转到错误块并继续进行下一次迭代。我想完全停止循环,有没有办法做到这一点?目前,如果我想停止循环,我必须杀死内核,这意味着再次加载模型等,这需要时间。

示例:我想知道是否有一种方法可以在我输入错误时中断整个 for 循环,而不是只中断一次迭代。

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

你可以break跳出循环:

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

只需在 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')

更多信息:https://www.delftstack.com/howto/python/keyboard-interrupt-python/