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

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

    import signal
    import sys
    import time
    
    def cleanup(*args):
        print 'Exiting'
        sys.exit(0)
    
    signal.signal(signal.SIGINT, cleanup)
    signal.signal(signal.SIGTERM, cleanup)
    while True:
        time.sleep(60)  # less busy loop
    

提交回复
热议问题