6

I currently have a Console based python program running under windows. The program maintains most of its data in memory and periodically saves the data to disk, or when the user shuts the application down via a Keyboard interrupt (Ctrl + C) event.

The problem i have is that when a user hits the "X" button at the top right of the console window, the session closes and the data in memory is lost. What i am looking for is an event/signal or hook so that i can clean up the memory before closing down.

I am hoping to do this without any external libraries, though if this is not possible i'd still like to know how it can be done.

1
  • I believe listening for the "X" button is platform-specific.
    – dappawit
    Commented Mar 17, 2011 at 3:44

1 Answer 1

7

In windows

if you are using pywin32, you can perform an event before the console is closed, I'm not sure this will tell you who or what is closing it, but maybe this gets you half way. You might also want to check out: Prevent a console app from closing ...

def on_exit(signal_type):
   print('caught signal:', str(signal_type))

import win32api
win32api.SetConsoleCtrlHandler(on_exit, True)

For those who come across this and use Linux...

the SIGHUP signal is thrown (signal hang up) when you close an SSH session/window.

import signal

signal.signal( signal.SIGHUP, handler )

def handler(signum, frame):
  #this is called when the terminal session is closed
  #do logic before program closes
  pass
3
  • This does not seem to work if the user closes the window with the "X" button under windows. Commented Mar 17, 2011 at 4:31
  • atexit doesn't catch Windows X close
    – Lior Dahan
    Commented Oct 22, 2020 at 13:23
  • updated the example with the wind32api.SetConsoleCtrlHandler - this works in a broader set of cases, but requires pywin32
    – Ben DeMott
    Commented Oct 22, 2020 at 17:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.