我的问题是;
我想在程序终止或计算机关闭时调用一个函数。
我在网上搜索了一下,我找到了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)
在评论区推荐一下就可以了,但不是我想要的。当所有代码都被执行时,它会打印“再见”,而不是在终止或 pc 关闭时。
我希望它清楚,提前致谢。
python 2.7 赢 8 64
最佳答案
请注意,atexit
函数不会在程序中断时调用,仅在程序正常结束时调用。更具体地说,来自文档:
Functions thus registered are automatically executed upon normal interpreter termination.
您需要使用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:~ $
关于python - 当程序终止或 pc 关闭时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653061/