KeyboardInterrupt
KeyboardInterrupt
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
data = process_batch() # Ctrl+C kills immediately, losing work
KeyboardInterruptWhat causes this error
The user pressed Ctrl+C (or sent SIGINT on Unix) to interrupt the running program.
How to fix it
Use try/except KeyboardInterrupt for graceful shutdown. Save partial work in a finally block. For long-running processes, implement signal handlers with the `signal` module for more control.
Code that causes this error
while True:
data = process_batch() # Ctrl+C kills immediately, losing workFixed code
try:
while True:
data = process_batch()
save_checkpoint(data)
except KeyboardInterrupt:
print("\nInterrupted — saving progress...")
save_checkpoint(data)About KeyboardInterrupt
KeyboardInterrupt is raised when the user presses Ctrl+C (or the interrupt key for their platform). Like SystemExit, it inherits from BaseException rather than Exception, so `except Exception` does not catch it. This design ensures that users can always abort a running program.
KeyboardInterrupt can happen at almost any point during execution, which makes it important for long-running code to handle it gracefully — for example, saving partial results, closing network connections, or cleaning up temporary files. Use try/except KeyboardInterrupt or try/finally blocks to implement graceful shutdown. In asyncio code, KeyboardInterrupt works differently and may need special handling.
The `signal` module provides lower-level control over interrupt handling if you need to defer or customize the interrupt behavior.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them