Bind key press to call function

S

Steven D'Aprano

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:
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.
 
C

Chris Angelico

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

I assume there's a reason for not using Ctrl-C and SIGINT with the
signal module?

This looks like the classic "sigint handler sets a flag that the main
loop polls" structure.

ChrisA
 
S

Steven D'Aprano

I assume there's a reason for not using Ctrl-C and SIGINT with the
signal module?

Yes, I want to leave Ctrl-C alone and have a similar, but separate,
signal handler (or equivalent).
This looks like the classic "sigint handler sets a flag that the main
loop polls" structure.

Exactly. I am open to alternative methods if they are lightweight.
 
C

Chris Angelico

Exactly. I am open to alternative methods if they are lightweight.

Might be easiest to spin off a thread to do the work, and then have
the main thread block on the keyboard.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top