在python3中使用SIGINT终止函数

2024-09-24 16:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

以以下代码为例:

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。在


Tags: 函数代码inimportyouforsignaltime
2条回答

您可以使用KeyboardInterrupt异常,而不是定义自己的SIGINT处理程序:

while input("Do you want to count? ").strip().casefold() == "yes":
    try:
        counter()
    except KeyboardInterrupt:
        print("You pressed ctrl-c")

您可以在stop中引发异常,该异常将停止counter的执行,并搜索最近的异常处理程序(在while True循环中设置)。在

也就是说,创建自定义异常:

class SigIntException(BaseException): pass

stop中升起:

^{pr2}$

并在while循环中捕获它:

while True:
    if(input("Do you want to count? ")=="yes"):
        try:        
            counter()
        except SigIntException:
            pass

它的行为符合你的需要。在

相关问题 更多 >