问题
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
回答1:
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.
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/18973238/can-i-make-use-of-an-interrupt-to-print-a-status-while-still-continue-process