Run atexit() when python process is killed

前端 未结 3 1644
小蘑菇
小蘑菇 2021-02-05 11:38

I have a python process which runs in background, and I would like it to generate some output only when the script is terminated.

def handle_exit():
    print(\'         


        
3条回答
  •  [愿得一人]
    2021-02-05 12:26

    Try signal.signal. It allows to catch any system signal:

    import signal
    
    def handle_exit():
        print('\nAll files saved in ' + directory)
        generate_output()
    
    atexit.register(handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)
    signal.signal(signal.SIGINT, handle_exit)
    

    Now you can kill {pid} and handle_exit will be executed.

提交回复
热议问题