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

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

    import time
    
    try:
        time.sleep(10)
    finally:
        print "clean up"
        
    clean up
    Traceback (most recent call last):
      File "", line 2, in 
    KeyboardInterrupt
    

    If you need to catch other OS level interrupts, look at the signal module:

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

    Signal Example

    from signal import *
    import sys, time
    
    def clean(*args):
        print "clean me"
        sys.exit(0)
    
    for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
        signal(sig, clean)
    
    time.sleep(10)
    

提交回复
热议问题