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.

JavaScript

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