以以下代码为例:
import signal
import time
def stop(signal, frame):
print("You pressed ctrl-c")
# stop counter()
def counter():
for i in range(20):
print(i+1)
time.sleep(0.2)
signal.signal(signal.SIGINT, stop)
while True:
if(input("Do you want to count? ")=="yes"):
counter()
如何让stop()
函数终止或中断{
输出示例:
^{pr2}$我使用的是python3.5.2。在
您可以使用
KeyboardInterrupt
异常,而不是定义自己的SIGINT
处理程序:您可以在
stop
中引发异常,该异常将停止counter
的执行,并搜索最近的异常处理程序(在while True
循环中设置)。在也就是说,创建自定义异常:
在
^{pr2}$stop
中升起:并在
while
循环中捕获它:它的行为符合你的需要。在
相关问题 更多 >
编程相关推荐