[Python] How to make a python program execute a function when it is closed

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I want to add an auto save on close feature to my program. I asked GPT for help, and it suggested using SIGNAL or win32api to capture the close signal, but both can only work successfully when closing with Ctrl+C. I want the function to work even when the program terminal is closed.

    For example, if you forget to close the program before shutting down the computer, it can also automatically perform the save function.

    Here is what GPT suggest

    import signal
    from time import sleep
    def handle_exit(signum, frame):
    # do something
    with open('text.txt','w',encoding='utf-8') as f:
    f.write(f"signal receive:{signum}")

    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    while 1:
    sleep(1)


    I test the program, when I directly close the windows of program, it will not write to file.

    Continue reading...

Compartilhe esta Página