Bind key press to call function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Nov 23 22:55:56 EST 2011


I'm looking for a way to interrupt a long-running function on a key 
press, but without halting the function.

E.g. if I have these two functions:

def handler(*args):
    print "caught interrupt and continuing..."


def exercise_cpu():
    for i in range(8):
        print "working..."
        for j in range(1000000):
            pass
    print "done"


and I call exercise_cpu(), then type some key combination (say, Ctrl-x-p 
for the sake of the argument), I'd like the result to look something like 
this:

>>> exercise_cpu()
working...
working...
working...
working...
working...
working...
caught interrupt and continuing...
working...
working...
done


I think I want to use the readline module to catch the key press Ctrl-x-p 
and generate a signal, say SIGUSR1, then use the signal module to install 
a signal handler to catch SIGUSR1. Is this the right approach, or is 
there a better one? Does anyone show me an example of working code that 
does this?

Linux only solutions are acceptable.


-- 
Steven



More information about the Python-list mailing list