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.