Skip to content
Advertisement

Simplest method to call a function from keypress in python(3)

I have a python application in which a function runs in a recursive loop and prints updated info to the terminal with each cycle around the loop, all is good until I try to stop this recursion.

It does not stop until the terminal window is closed or the application is killed (control-c is pressed) however I am not satisfied with that method.

I have a function which will stop the loop and exit the program it just never has a chance to get called in the loop, so I wish to assign it to a key so that when it is pressed it will be called.

What is the simplest method to assign one function to one or many keys?

Advertisement

Answer

You can intercept the ctrl+c signal and call your own function at that time rather than exiting.

import signal
import sys

def exit_func(signal, frame):
    '''Exit function to be called when the user presses ctrl+c.
    Replace this with whatever you want to do to break out of the loop.
    '''
    print("Exiting")
    sys.exit(0) # remove this if you do not want to exit here

# register your exit function to handle the ctrl+c signal
signal.signal(signal.SIGINT, exit_func)

#loop forever
while True:
    ...

You should replace sys.exit(0) with something more useful to you. You could raise an exception and that except on it outside the loop body (or just finally) to perform your cleanup actions.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement