Skip to content Skip to sidebar Skip to footer

Python - How To Detect When User Closes A Console Application Via "x" Button

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 sh

Solution 1:

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 ...

defon_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 )

defhandler(signum, frame):
  #this is called when the terminal session is closed#do logic before program closespass

Post a Comment for "Python - How To Detect When User Closes A Console Application Via "x" Button"