How to run one last function before getting killed in Python?

前端 未结 5 1944
不思量自难忘°
不思量自难忘° 2020-12-08 20:17

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.

5条回答
  •  情话喂你
    2020-12-08 20:50

    You could use the atexit module. With it, you can register a function which will be called at program termination. An example from here: http://docs.python.org/library/atexit.html

    try:
        _count = int(open("/tmp/counter").read())
    except IOError:
        _count = 0
    
    def incrcounter(n):
        global _count
        _count = _count + n
    
    def savecounter():
        open("/tmp/counter", "w").write("%d" % _count)
    
    import atexit
    atexit.register(savecounter)
    

    You can also pass positional and keyword parameters to the function you want to call at program termination.

    Note that there are a few circumstances listed in the docs in which your handler won't be called:

    Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.

    As such, you may want to also register a signal handler.

提交回复
热议问题