如何在Python中杀死之前运行最后一个函数? [英] How to run one last function before getting killed in Python?
本文介绍了如何在Python中杀死之前运行最后一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以在运行的Python脚本被其他脚本,键盘中断等终止之前运行最后一个命令。
解决方案
进口时间
尝试:
time.sleep(10)
终于:
printclean up
清理
Traceback(最近一次调用最后一次):
在< module>中,第2行的文件< stdin>
KeyboardInterrupt
如果您需要捕获其他操作系统级别的中断,请查看信号模块:
http://docs.python。 org / library / signal.html
信号示例
从信号导入*
导入sys,时间
def clean(* args):
打印clean me
sys.exit(0)$ b (SIGABRT,SIGBREAK,SIGILL,SIGINT,SIGSEGV,SIGTERM)中的
$ b:
信号(sig,clean)
time.sleep(10)
Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.
解决方案
import time
try:
time.sleep(10)
finally:
print "clean up"
clean up
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
If you need to catch other OS level interrupts, look at the signal module:
http://docs.python.org/library/signal.html
Signal Example
from signal import *
import sys, time
def clean(*args):
print "clean me"
sys.exit(0)
for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
signal(sig, clean)
time.sleep(10)
这篇关于如何在Python中杀死之前运行最后一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文