2

I want to capture command window close event from Python.
In other words, when the user tries to close the command prompt window, script should detect it and display a message like Do you really want to exit - Yes/No

Any suggestions about how to implement this? Please help me in doing this.

1
  • What platform are you on? Windows? Commented Mar 3, 2011 at 12:01

1 Answer 1

4

define like this:

import time

def on_exit(sig, func=None):
    print("exit handler")
    time.sleep(10)  # so you can see the message before program exits
  • Windows:

if you install pywin32 package, you can :

import win32api
win32api.SetConsoleCtrlHandler(on_exit, True)
  • Un*x:

Or, using python internal "signal" library, if you are using under *nix system:

import signal
signal.signal(signal.SIGTERM, on_exit)
2
  • I tried No. 2 but it didn't work (the exit handler was never called). I am using Python 2.7
    – James
    Commented Dec 18, 2012 at 13:46
  • If you are on Windows, opt for win32api Commented Mar 6, 2020 at 9:22

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