views:

469

answers:

1

I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).

I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it is handled, it has already interrupted a system call.

I'd like something equivalent to the *nix "raw" mode. Just let the input queue up and when it is safe for my application to read it, it will.

Maddeningly enough, msvcrt.getch() seems to return Control-C as a character. But that only works while the program is blocked by getch() itself. If I am in another system call (sleep, just to use an example), I get the SIGINT.

+2  A: 

You need to call the win32 API function SetConsoleCtrlHandler with NULL (0) as its first parameter and TRUE (1) as its second parameter. If you're already using pywin32, win32.SetConsoleCtrlHandler is fine for the purpose, otherwise ctypes should work, specifically via ctypes.windll.kernel32.SetConsoleCtrlHandler(0, 1)/

Alex Martelli
Thanks! That seems to work (keeps sleep from being interrupted). Oddly enough, it causes the interactive prompt to exit and dump me back to the cmd.com window. That's not a problem for my application, just a curiosity.
I should say the behaviour in my previous comment was with ctypes, no pywin32, if that matters (oh, and I'm back in the stone age with Python24 :) ).
@dgou, always glad to help (if an answer decisively help solve your problem, remember to accept it: that's stack overflow etiquette!-).
Alex Martelli
Yes, it is very close. Interestingly, while Ctrl-C handling is disabled, the key event is completely swallowed. My primary goal is to prevent the interruption. It would have been nicer to get the character:ctypes.windll.kernel32.SetConsoleCtrlHandler(0, 1)time.sleep(10) # during which I type ^Cmsvcrt.get() # hangs waiting for a character.# if I type A instead of ^C then getch() returns it without hanging.Again, not a big deal, just this and the interactive prompt behaviour are curiosities. :)Thanks again!