Skip to content

Instantly share code, notes, and snippets.

@itamarst
Created March 31, 2020 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itamarst/d3c9919753f03cc329130c1d6de5d8f9 to your computer and use it in GitHub Desktop.
Save itamarst/d3c9919753f03cc329130c1d6de5d8f9 to your computer and use it in GitHub Desktop.
Typing Ctrl-C in Powershell interrupts the input() with KeyboardInterrupt, so why doesn't GenerateConsoleCtrlEvent?
import threading
import time
from _thread import interrupt_main
import signal
import os
import ctypes
def interrupter():
time.sleep(1) # make sure input() is waiting
print("Interrupting!")
import os, win32api
ctypes.CDLL("Kernel32").GenerateConsoleCtrlEvent(0, 0)
print("Should be interrupted?!")
time.sleep(3)
print("Where's my KeyboardInterrupt?")
def main():
t = threading.Thread(target=interrupter, daemon=True).start()
input("Waiting for input:")
main()
@itamarst
Copy link
Author

itamarst commented Mar 31, 2020

I am trying to have a thread cause a KeyboardInterrupt that interrupts the input(), in order to fix a bug in Jupyter where pdb is uninterruptible on Windows. Windows documentation suggests GenerateConsoleCtrlEvent.

But the above program when run only does KeyboardInterrupt after I press enter, i.e after input() finishes.

Yet if I type Ctrl-C on the keyboard, input() does get interrupted. How do I emulate that?

@itamarst
Copy link
Author

Python 3.8.2 on Windows 10 Pro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment