With most Python interpreters that I've used, Ctrl+C will cause the interpreter to print out "KeyboardInterrupt
" and remain open. However, in a recent install on a new computer, Ctrl+C is causing the interpreter to exit, which is undesirable.
signal.SIGINT
handler still exits.raise KeyboardInterrupt
doesn't exit the interpreter.^C
is emitted before exit.If I Ctrl+C during the snooze in the following snippet, the interpreter remains open.
import time
try:
time.sleep(100)
except KeyboardInterrupt:
pass
Environment: Python 3.4.3 on Windows 10
key_down() – This method performs the action sending a key press only and not releasing it. The key_down() method is a part of Action Chains class. This method is widely used for coping and pasting actions via (ctrl+c, ctrl+v).
In layman's terms, exceptions are anything that disrupts the program's normal flow. Similarly, KeyboardInterrupt is a Python exception that is thrown when a user or programmer interrupts a program's usual execution. While executing the program, the Python interpreter checks for any interrupts on a regular basis.
Ctrl+C handling is broken at the shell prompt for Python versions prior to 3.6 when run on Windows 8 and above. It's also broken for input
and raw_input
, for which you'll get an EOFError
instead of a KeyboardInterrupt
. You can fix this by installing and enabling win_unicode_console
-- or by upgrading to 3.6
The problem is that Python's old code for reading from the console depends on ReadFile
setting the last error to ERROR_OPERATION_ABORTED
(995) when reading is interrupted by Ctrl+C. In Windows 8, Microsoft completely rewrote how client processes talk to the console. In so doing they broke the documented contract for the behavior of ReadFile
in this case. Without the error, Python thinks the aborted read was a successful read of 0 bytes. Normally this indicates end of file (EOF
), so the REPL simply quits as if the user had typed Ctrl+Z, Enter.
ReadFile
is a generic read from any File handle. There is also a specialized ReadConsole
function. This one still behaves correctly, which is why win_unicode_console
and 3.6+ don't have this problem. They call ReadConsoleW
to solve the separate problem of using the full range of Unicode in the console, and this just happens to also solve the Ctrl+C problem.
FYI, the ^C
that you see on the screen isn't written by the console (conhost.exe) or Python. It's actually printed by the CTRL_BREAK_EVENT
handler that's set by the cmd.exe shell. If you run Python from PowerShell, you shouldn't see this printed with Ctrl+Break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With