KeyboardInterrupt in Python — What It Means and How to Fix It

What Python's KeyboardInterrupt exception means and how to resolve it.

Published October 28, 2026

KeyboardInterrupt is raised when the user presses Ctrl+C. It lets scripts stop cleanly.

What it means and why it happens

It is not an error but an exit signal. Catch it to clean up, then exit.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
KeyboardInterrupt

Practical examples

Code that triggers it

while True:
    pass   # Ctrl+C raises KeyboardInterrupt

The fix

try:
    while True:
        work()
except KeyboardInterrupt:
    print('Stopping')
    cleanup()

Context manager cleanup

try:
    run()
finally:
    cleanup()

Common mistakes

  • Swallowing it with bare except:.
  • Not cleaning up resources.
  • Catching it and continuing forever.

Key takeaways

  • KeyboardInterrupt: KeyboardInterrupt is raised when the user presses Ctrl+C.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Why avoid bare except?

It catches KeyboardInterrupt and SystemExit, making scripts hard to stop.

How do I find which line caused KeyboardInterrupt?

The error message and stack trace show the file and line; start there and work backwards.

More Python articles