Search code examples
pythonwindowsconsole

How do I run a function when the console window is closed?


I have a main process (main.py) that is designed to run forever. It will only stop running when I close the console window. This is bundled as an .exe that I create using PyInstaller.

When I close the console window, I need it to run a function logout, which sends an HTTP request to an AWS Lambda function.

How do I accomplish this?


Solution

  • To answer my own question for future users;

    import win32con
    import win32api
    
    win32api.SetConsoleCtrlHandler(exit_handler, 1)
    
    
    def logout():
        # do something
    
    
    def exit_handler(event):
        if event in [win32con.CTRL_C_EVENT, win32con.CTRL_LOGOFF_EVENT,
                             win32con.CTRL_BREAK_EVENT, win32con.CTRL_SHUTDOWN_EVENT,
                             win32con.CTRL_CLOSE_EVENT]:
            logout()
    

    Where logout is the function I want to run on console closure.

    Be advised that you will want to only register the function once, as the same function can and will be registered more than once if you call SetConsoleCtrlHandler multiple times.

    It may also be a good practice to have a global flag of sorts, that will make sure the exit handler runs only once in the event of Windows sending multiple CTRL events.

    If your logout function takes more than 1-2 seconds to execute, the entire function may not run, as most console CTRL events are not ones that can be caught - they are solely alerts that Windows is about to end your process, and it is not possible to prevent closure.