Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 253
user2497792 Avatar asked Jul 13 '26 07:07

user2497792


1 Answers

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.

like image 162
Ryan Haining Avatar answered Jul 15 '26 22:07

Ryan Haining



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!