Raised when the user interrupts program execution, usually by pressing Ctrl+C.
A KeyboardInterrupt error occurs when a running Python program is interrupted by the user, typically by pressing Ctrl+C (or Ctrl+Break on some systems) in the terminal. This raises the KeyboardInterrupt exception, which can be caught and handled by the program. If not handled, the program will terminate.
# Running this script and pressing Ctrl+C will immediately terminate it without cleanup.
while True:
pass# This script handles KeyboardInterrupt and performs cleanup before exiting.
try:
while True:
pass
except KeyboardInterrupt:
print('Interrupted by user. Cleaning up...')