Can I make use of an interrupt to print a status while still continue process?

我只是一个虾纸丫 提交于 2020-01-06 07:58:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!