Eddie Hart Eddie Hart - 1 month ago 11
Python Question

Using SIGINT to kill a function in Python 3

Take the following code as an example:

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()


How would I get the
stop()
function to kill, or break, the
counter()
function so it returns to the prompt?

Output example:

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?


I'm using Python 3.5.2.

Answer

You could raise an exception in stop which will halt execution of counter and search for the closest exception handler (which you set in the while True loop).

That is, create a custom exception:

class SigIntException(BaseException): pass

Raise it in stop:

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

and catch it in your while loop:

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

and it behaves the way you need it to.