使用SIGINT杀死Python 3中的函数

时间:2016-11-05 12:28:49

标签: python python-3.x asynchronous subprocess python-asyncio

以下面的代码为例:

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()函数来杀死或破坏counter()函数,以便它返回到提示符?

输出示例:

Do you want to count? no
Do you want to count? yes
1
2
3
4
5
6
7
You pressed ctrl-c
Do you want to count?

我正在使用Python 3.5.2。

2 个答案:

答案 0 :(得分:1)

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

即创建自定义异常:

class SigIntException(BaseException): pass

stop

中提升它
def stop(signal, frame):
    print("You pressed ctrl-c")
    raise SigIntException

并在while循环中抓住它:

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

它的行为与你需要的方式相同。

答案 1 :(得分:1)

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

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