在python中处理KeyboardInterrupt后如何返回执行循环

问题描述

我有一个看起来像这样的代码

some_list = []
try:
    while True:
        ... code that uses the list ...
except KeyboardInterrupt:
    ... code that modifies the list ...

处理完这个异常后,如何在不嵌套循环的情况下返回执行这个循环?

解决方法

您可以简单地重新构建代码以将循环与 try/catch

以这个为例:

from time import sleep

some_list = []

while True:
    try:
        print(some_list)
        sleep(1)
    except KeyboardInterrupt:
        some_list.append("1")