[英]Saving program state when user invokes Ctrl-C
In python, when the user invokes Ctrl-C, what happens? 在python中,当用户调用Ctrl-C时会发生什么? Do I have the possibility to save the program state?
我是否有可能保存程序状态?
What about context-managers? 上下文管理器怎么样? Does the
__exit__()
section get executed? __exit__()
部分是否被执行?
Basically, a KeyboardInterrupt
exception is raised inside the main thread. 基本上,在主线程内引发了
KeyboardInterrupt
异常。 So yes, you can handle it by catching it in try/except block and __exit__()
sections are executed 所以,是的,您可以通过在try / except块中捕获它来处理它,并执行
__exit__()
部分
https://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt https://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt
This is what the atexit module is for. 这就是atexit模块的用途。 You can register multiple exit handlers.
您可以注册多个退出处理程序。 You can see it at work by running this program and observing that a message is displayed:
您可以通过运行此程序并观察显示的消息来查看它的工作情况:
import atexit
@atexit.register
def exithandler():
print("Exit trapped!")
if __name__ == '__main__':
while True:
pass
I'll just mention signal which is also a built in that can handle Ctrl + C and many more signals such as SIGHUP
etc. 我只会提到一个内置的信号 ,它可以处理Ctrl + C和更多信号,如
SIGHUP
等。
import signal
def signal_handler(signal, frame):
# Do work
# Thread cleanup
# pickle program state
# remove(pidfile) # as an example
exit(0)
signal.signal(signal.SIGINT, signal_handler)
This is just a example of a broad framework that can handle numerous signals. 这只是一个可以处理大量信号的广泛框架的例子。
Here's a list of some of the signals you could catch. 这是您可以捕获的一些信号的列表 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.