我的问题是;
我希望在程序终止或计算机关闭时调用一个函数。
我在网上搜索过,我找到了atexit,这里有一个示例程序来告诉我想要的东西
import atexit
a = 1
b = 0
while a==1:
b += 1
#if b=30:
#a=2
def say_bye():
print " Goodbye "
atexit.register(say_bye)
如果推荐评论部分,它会起作用,但这不是我想要的。当所有代码执行完毕而不是终止或关机时,它会打印“Goodbye”。
我希望很清楚,先谢谢。
Python 2.7 赢8 64
答案 0 :(得分:3)
请注意,只有在程序正常完成时,才会在程序中断时调用atexit
函数。更具体地说,来自doc:
这样注册的功能会在正常情况下自动执行 口译员终止。
您需要使用signal
模块
$ cat t.py
import signal
def say_bye(signum, frame):
print " Goodbye "
exit(1)
signal.signal(signal.SIGINT, say_bye)
a = 1
b = 0
while a==1:
b += 1
这个程序启动一个无限循环,但它已经为SIGINT注册了一个信号处理程序,当用户点击 Ctrl + C 时发送的信号。
$ python t.py
^C Goodbye
$
请注意,如果没有exit(1)
命令,程序将不会被 Ctrl + C 终止:
$ python t.py
^C Goodbye
^C Goodbye
^C Goodbye
^C Goodbye
^Z
[1]+ Stopped python t.py
我需要发送另一个信号(SIGSTOP)来阻止它。
点击 Ctrl + C 后,会显示Goodby消息。您可以使用SIGTERM执行相同的操作,即使用kill
命令发送的信号:
$ cat t.py
import signal
def say_bye(signum, frame):
print " Goodbye "
exit(1)
signal.signal(signal.SIGTERM, say_bye)
a = 1
b = 0
while a==1:
b += 1
以上代码给出:
$ python t.py & PID=$! ; sleep 1 && kill $PID
[1] 94883
Goodbye
[1]+ Exit 1 python t.py
francois@macdam:~ $