0
0
PythonDebug / FixBeginner · 3 min read

How to Handle Keyboard Interrupt in Python: Simple Guide

In Python, you handle a keyboard interrupt by catching the KeyboardInterrupt exception using a try-except block. This lets your program stop gracefully when you press Ctrl+C instead of crashing.
🔍

Why This Happens

When you press Ctrl+C while a Python program is running, it raises a KeyboardInterrupt exception. If you don't catch this exception, the program stops immediately and shows an error message.

python
while True:
    print("Running...")
Output
Running... Running... ^CTraceback (most recent call last): File "script.py", line 2, in <module> while True: KeyboardInterrupt
🔧

The Fix

Wrap your code in a try block and catch KeyboardInterrupt in an except block. This way, you can print a message or clean up before the program ends.

python
try:
    while True:
        print("Running...")
except KeyboardInterrupt:
    print("Program stopped by user.")
Output
Running... Running... Program stopped by user.
🛡️

Prevention

Always use try-except KeyboardInterrupt when running loops or long tasks to allow graceful exits. This avoids abrupt stops and lets you save data or release resources properly.

Use clear messages to inform users the program stopped by their action.

⚠️

Related Errors

Other exceptions like SystemExit or EOFError can also stop programs unexpectedly. Handling KeyboardInterrupt is specific to user interrupts (Ctrl+C).

For cleanup on any exit, use finally blocks or atexit module.

Key Takeaways

Use try-except to catch KeyboardInterrupt and stop your program gracefully.
Pressing Ctrl+C raises KeyboardInterrupt, which you can handle to avoid ugly errors.
Always handle KeyboardInterrupt in loops or long-running tasks for better user experience.
Use except block to clean up or save data before exiting.
Related exceptions like SystemExit need different handling for program termination.