Created
September 26, 2022 10:56
-
-
Save ultrafunkamsterdam/c0d92c416f313cfaa4f0f555871beb43 to your computer and use it in GitHub Desktop.
Python windows native console ctrl+c callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ctypes import wintypes as w | |
import ctypes as c | |
def handler( *args ): | |
print( 'Native console ctrl handler call:' , args ) | |
return 0 | |
HandlerRoutineType = c.WINFUNCTYPE( w.BOOL , w.DWORD ) | |
SetConsoleCtrlHandler = c.windll.kernel32.SetConsoleCtrlHandler | |
SetConsoleCtrlHandler.argtypes = (HandlerRoutineType , w.BOOL) | |
SetConsoleCtrlHandler.restype = w.BOOL | |
chandler = HandlerRoutineType( handler ) | |
retval = SetConsoleCtrlHandler( chandler , 1 ) | |
def test(): | |
n = 0 | |
import time | |
print( 'ignoring default python keyboarditerrupt. so to quit this program hit CTRL C 3 times' ) | |
while True: | |
try: | |
time.sleep( .001 ) | |
except KeyboardInterrupt as e: | |
if n >= 3: | |
break | |
n += 1 | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment