首页 > 解决方案 > 如何结束包含 time.sleep 的 while 循环?

问题描述

假设我有这样的代码:

import time
try:
    while True:
        print("Hello World")
        time.sleep(10)
except:
    print("Ctrl+z was pressed")  #Doesn't get executed

当我尝试在 python 3 中执行此代码时,我的 except 块中的内容不会执行。我能做些什么?

标签: python-3.x

解决方案


您将始终卡在 while 循环中,因为条件始终为 True。您将永远不会退出 try 条件,因此永远不会执行 except 块。

如果我是正确的,crtl+z 只会让程序休眠,所以没有像 crtl+c 这样的终止信号,它会打破循环并让 except 块执行。


推荐阅读