Run atexit() when python process is killed

前端 未结 3 1645
小蘑菇
小蘑菇 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:15

    To check your system and see which signal is being called:

    import signal
    import time
    
    
    def handle_signal(sig_id, frame):
        sig = {x.value: x for x in signal.valid_signals()}.get(sig_id)
        print(f'{sig.name}, {sig_id=}, {frame=}')
        exit(-1)
    
    
    for sig in signal.valid_signals():
        print(f'{sig.value}: signal.{sig.name},')
        signal.signal(sig, handle_signal)
    
    time.sleep(30)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 12:37

    To enable signals when debugging PyCharm on Windows:

    1. Within PyCharm hit Ctrl + Shift + A to bring up the "Find Actions..." menu
    2. Search for "Registry" and hit enter
    3. Find the key kill.windows.processes.softly and enable it (you can start typing "kill" and it will search for the key)
    4. Restart PyCharm
    0 讨论(0)
提交回复
热议问题