0

In python, is it possible to make use of KeyboardInterrupt or CTRL+C to print a status message, possibly like printing content of a variable and then continuing with the execution? Or will Interrupts always kill the process?

An example of what I would like to do:

def signal_handler(signum, frame):
    global interrupted
    interrupted = True

while true:
   update(V)
   if interrupted:
      print V
drum
  • 5,416
  • 7
  • 57
  • 91

3 Answers3

5

You can do this using a signal handler:

import signal

def sigint_handler(signum, frame):
     print "my_variable =", frame.f_locals.get("my_variable", None)

signal.signal(signal.SIGINT, sigint_handler)

Now interrupting the script calls the handler, which prints the variable, fishing it out of the current stack frame. The script then continues.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Same question I asked Kernonnes,: Using this method, can I specify to use a key other than CTRL+C to interrupt? I noticed that now I cant kill the program, so I would like to assign a different key to interrupt – drum Sep 24 '13 at 05:51
  • You can't use another key for SIGINT. Of course, you could use another signal and send it from the command line (assuming you're on Linux) using the `kill` command. – kindall Sep 24 '13 at 13:12
1

It can be done. The signal library provides this functionality, and it pretty much goes the way you prototyped.

import signal

interrupted = False

def signal_handler(signum, frame):
    global interrupted
    interrupted = True

signal.signal(signal.SIGINT, signal_handler)

while true:
    update(V)
    if interrupted:
        print V
kindall
  • 178,883
  • 35
  • 278
  • 309
Kernonnes
  • 36
  • 3
  • Using this method, can I specify to use a key other than CTRL+C to interrupt? I noticed that now I cant kill the program, so I would like to assign a different key to interrupt. – drum Sep 24 '13 at 05:45
  • 1
    There are a number of control-sequences that produce signals sent to the foreground program. The `signal` library will let you bind a handler to any signal your keyboard can send. That said, with ctrl-C bound to your debugging function, you can still use ctrl-\. It's a lesser-known kill command that sends SIGQUIT. It triggers a core dump, which would be useful if you were programming C or C++, but w/e. – Kernonnes Sep 25 '13 at 05:46
0

Pressing ctrl+c raises KeyboardInterrupt.

Catch KeyboardInterrupt and print a message from it, or use a state variable like you have above.

See: Capture Control-C in Python

Community
  • 1
  • 1
Ben DeMott
  • 3,362
  • 1
  • 25
  • 35