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

前端 未结 5 1937
不思量自难忘°
不思量自难忘° 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:46

    WIth apologies to 'Unknown' for taking their answer and correcting it as though it was my own answer, but my edits were rejected.

    The approved answer contains an error that will cause a segfault.

    You cannot use sys.exit() in a signal handler, but you can use os._exit so that it becomes:

    from signal import *
    import os, time
    
    def clean(*args):
        print "clean me"
        os._exit(0)
    
    for sig in (SIGABRT, SIGINT, SIGTERM):
        signal(sig, clean)
    
    time.sleep(10)
    

    SIGBREAK may be used if the target platform is Windows.

    Depending on the use case and the need to cleanup in the event of fatal errors - you may add SIGSEGV and SIGILL but generally this is not advised since the program state may be such that you create an infinite loop.

提交回复
热议问题