2016-11-05 67 views
1

功能以下面的代码为例:使用SIGINT杀死在Python 3

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。

回答

1

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

while input("Do you want to count? ").strip().casefold() == "yes": 
    try: 
     counter() 
    except KeyboardInterrupt: 
     print("You pressed ctrl-c") 
+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 

和它的行为你需要的方式。

+0

天才!感谢您的帮助; D –

+0

@EddieHart很清楚,Python中的默认SIGINT处理程序引发了KeyboardInterrupt异常,即您不需要在主线程中默认执行任何操作来中断您的'counter()'函数。 – jfs

+0

@ J.F.Sebastian是的,但据我所知,这将终止整个计划? –