【问题标题】:How does python handle KeyboardInterrupt during infinite loop?python如何在无限循环期间处理KeyboardInterrupt?
【发布时间】:2020-05-04 04:20:50
【问题描述】:

当我运行这段代码时:

while 1:
    try:
        pass
    except KeyboardInterrupt:
        pass

然后我按ctrl+c 尝试通过KeyboardInterrupt 终止程序,我通常会成功,但并不总是成功。大多数时候,我第一次尝试ctrl+c 会终止程序,但有时我需要按两次ctrl+c

与此代码比较:

from time import sleep

while 1:
    try:
        sleep(0.000000000000000000000000000000000000000000000000000000000000000000001)
    except KeyboardInterrupt:
        pass

使用这段代码,无论我按多少次ctrl+c,程序都不会终止。

我的假设是,在第一种情况下,我的 KeyboardInterrupt 通常有效,因为 pass 语句执行得如此之快,以至于我更有可能在 while 循环条件检查期间按 ctrl+c(不在 try 块中)比在 pass 语句执行期间(在 try 块中)。

并且,在第二个示例中,我假设 sleep 函数的执行时间必须比 while 循环条件检查长得多,这样我几乎可以保证在其执行期间按 ctrl+c(因此在 try 块中捕获 KeyboardInterrupt并继续循环)。

谁能证实我的假设或给出替代推理?

【问题讨论】:

    标签: python python-3.x error-handling while-loop keyboardinterrupt


    【解决方案1】:

    由于您在这两种情况下都在pass 处理键盘中断,因此程序将继续执行while 循环。

    对于第二种情况,由于 try 块主体中的 sleep,您的 KeyboardInterruptsleep 期间命中该过程的机会要高得多 - 这意味着您的 except块几乎可以保证被执行。这意味着你的程序只是继续。您可以通过在 except 块中添加打印来测试这一点。

    from time import sleep
    
    while 1:
        try:
            sleep(0.000000000000000000000000000000000000000000000000000000000000000000001)
        except KeyboardInterrupt:
            print('exc')
            pass
    

    如果我运行它并按Ctrl+C,我会得到:

    >python so_test.py
    exc
    exc
    exc
    exc
    exc
    exc
    exc
    exc
    

    每个Ctrl+C 都会执行except 块,但您的程序会继续运行。

    然而,在第一种情况下,由于try 块中没有任何延迟(即sleep),程序很可能在try 块之外执行(在进入它之前,或之后)当KeyboardInterrupt 命中您的进程时。这意味着您的异常未得到处理,并且程序结束。然而,如果中断命中try-block 内的进程,程序将继续。检查这个:

    while 1:
        try:
            pass
        except KeyboardInterrupt:
            print('exc')
            pass
    

    你可以得到这个:

    >python so_test.py
    exc
    exc
    exc
    exc
    Traceback (most recent call last):
      File "so_test.py", line 5, in <module>
        pass
    KeyboardInterrupt
    

    希望能解开疑惑。

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 2012-04-07
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2021-08-21
      相关资源
      最近更新 更多