程序退出前做一些事情

问题描述 投票:0回答:6

如何才能在程序退出之前执行某个函数或某些内容?我有一个脚本将在后台不断运行,我需要它在退出之前将一些数据保存到文件中。有标准的方法吗?

python function exit
6个回答
282
投票

查看

atexit
模块:

http://docs.python.org/library/atexit.html

例如,如果我想在应用程序终止时打印一条消息:

import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)

请注意,这对于正常终止脚本非常有用,但它不会在所有情况下都被调用(例如致命的内部错误)。


45
投票

如果您希望某些东西始终运行,即使出现错误,请像这样使用

try: finally:
-

def main():
    try:
        execute_app()
    finally:
        handle_cleanup()

if __name__=='__main__':
    main()

如果您还想处理异常,可以在

except:
 之前插入 
finally:


29
投票

如果您通过引发

KeyboardInterrupt
来停止脚本(例如按 Ctrl-C),您可以将其作为标准异常捕获。你也可以用同样的方式捕捉
SystemExit

try:
    ...
except KeyboardInterrupt:
    # clean up
    raise

我提到这一点只是为了让您了解这一点;执行此操作的“正确”方法是上面提到的

atexit
模块。


8
投票

这是根据其他答案改编的版本。 它应该可以正常退出、终止和 PyCharm 停止按钮(我可以确认的最后一个)(尚未完全测试)。

import signal
import atexit


def handle_exit(*args):
    try:
        ... do computation ...
    except BaseException as exception:
        ... handle the exception ...


atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)

4
投票

如果您有在程序的整个生命周期中都存在的类对象,您还可以使用

__del__(self)
方法从类中执行命令:

class x:
def __init__(self):
    while True:
        print ("running")
        sleep(1)

def __del__(self):
    print("destructuring")


a = x()

这也适用于正常程序结束,如果执行被中止,肯定会有一些例外:

running
running
running
running
running
Traceback (most recent call last):
  File "x.py", line 14, in <module>
    a = x()
  File "x.py", line 8, in __init__
    sleep(1)
KeyboardInterrupt
destructuring

1
投票

这可以处理正常退出以及使用

kill
Ctrl+C
终止进程:

import sys
import atexit
import signal

def exit_handler():
    print("Cleaning up")

def kill_handler(*args):
    sys.exit(0)

atexit.register(exit_handler)
signal.signal(signal.SIGINT, kill_handler)
signal.signal(signal.SIGTERM, kill_handler)

# MAIN PROGRAM
# for example just reading from the input:
input("Press enter: ")

© www.soinside.com 2019 - 2024. All rights reserved.