KeyboardInterrupt Exception in Python Explained

KeyboardInterrupt is a Python exception that happens when you stop a running program from the keyboard. In most cases, this means you pressed Ctrl+C in the terminal.

This page explains what KeyboardInterrupt means, when it appears, and how to handle it safely. It is usually not a bug in your code. Instead, it means the program was interrupted by the user.

Quick fix #

If you want your program to stop cleanly when the user presses Ctrl+C, wrap the code in a try-except block:

try:
    while True:
        print("Running...")
except KeyboardInterrupt:
    print("\nProgram stopped by user")

Use this when you want to avoid a long traceback and show a friendly exit message instead.

What KeyboardInterrupt means #

KeyboardInterrupt is a built-in exception in Python.

It means:

  • The program was interrupted from the keyboard
  • This usually happens when you press Ctrl+C
  • It is not usually caused by a coding mistake
  • It often appears when a program is stuck in a loop, waiting for something, or running for a long time

If you are new to exceptions, see Python errors and exceptions explained.

When this exception happens #

You may see KeyboardInterrupt in situations like these:

  • During an infinite while loop
  • While waiting for user input
  • During a long-running task
  • While time.sleep() is pausing the program
  • When a script is processing a lot of data and you stop it manually

For example, a script may keep running until you interrupt it because it has no normal stop condition. This is common with Python while loops.

Example that causes KeyboardInterrupt #

Here is a simple program that keeps running forever:

while True:
    print("Still running...")

This loop has no end. If you run it in a terminal, it will continue printing until you stop it.

A common way to stop it is to press Ctrl+C. When you do, Python may show a traceback ending with KeyboardInterrupt.

A more realistic example uses a small delay:

import time

while True:
    print("Working...")
    time.sleep(1)

Possible output before interruption:

Working...
Working...
Working...
^CTraceback (most recent call last):
  ...
KeyboardInterrupt

In this example:

  • while True creates an infinite loop
  • time.sleep(1) pauses for 1 second each time
  • Pressing Ctrl+C interrupts the program while it is running or sleeping

If you want to understand that delay function better, see time.sleep() explained.

How to fix or handle it #

KeyboardInterrupt usually does not need a “fix” in the same way as a normal error. Instead, you decide whether the program should:

  • Stop immediately
  • Stop cleanly with a message
  • Save data before exiting

Here are the main ways to handle it.

1. Press Ctrl+C only when you want to stop the program #

If you manually interrupted the script, then KeyboardInterrupt is expected.

In that case, nothing may be wrong. You simply stopped the program on purpose.

2. Catch KeyboardInterrupt for a clean exit #

Use try-except if you want to show a friendly message instead of a traceback.

try:
    while True:
        print("Running...")
except KeyboardInterrupt:
    print("\nProgram stopped by user")

This is a simple use of exception handling. If you need more help with the syntax, see using try, except, else, and finally in Python.

3. Use a proper loop condition when possible #

Infinite loops are sometimes useful, but many programs should stop normally.

Instead of this:

while True:
    print("Checking...")

You can often use a condition:

count = 0

while count < 3:
    print("Checking...")
    count += 1

print("Done")

This version ends by itself and does not need manual interruption.

4. Add a break condition #

If you do need while True, add a way to exit the loop.

while True:
    text = input("Type quit to stop: ")

    if text == "quit":
        break

    print("You typed:", text)

print("Program ended normally")

This lets the user stop the program without pressing Ctrl+C.

5. Save work before exiting if needed #

If your program writes to a file, stores data, or keeps a network connection open, you may want to clean up before exit.

try:
    while True:
        print("Program is running...")
except KeyboardInterrupt:
    print("\nSaving progress before exit...")

For some programs, a clean shutdown is important.

How to exit cleanly #

A clean exit means your program stops in a controlled way.

This is helpful when you want to:

  • Print a friendly message
  • Close files
  • Close connections
  • Save progress
  • Always run cleanup code

Here is a simple example with finally:

try:
    print("Program started")
    while True:
        pass
except KeyboardInterrupt:
    print("\nInterrupted by user")
finally:
    print("Cleanup code runs before exit")

What this does:

  • try runs the main code
  • except KeyboardInterrupt handles Ctrl+C
  • finally runs whether an interruption happens or not

If something must always happen before the program ends, finally is a good choice.

In some programs, you may also choose to exit intentionally with sys.exit(), but that is different from a user pressing Ctrl+C.

Also, avoid catching KeyboardInterrupt and doing nothing unless you have a good reason. Hiding the interruption can make your program harder to stop and harder to debug.

Debugging steps #

If you see KeyboardInterrupt and are not sure why, try these steps:

  • Check whether you pressed Ctrl+C
  • Look for infinite loops
  • Check for slow code that seems stuck
  • Look for input() calls waiting for user input
  • Check for long sleep() delays
  • Add print() statements to see where the program stops

Helpful commands:

python script.py
python -u script.py
python -m pdb script.py

What they do:

  • python script.py runs the script normally
  • python -u script.py runs Python in unbuffered mode, so output appears immediately
  • python -m pdb script.py starts the Python debugger

If you want more help tracking problems step by step, see the beginner guide to debugging Python code.

KeyboardInterrupt vs other exceptions #

KeyboardInterrupt is different from many common Python exceptions.

For example:

  • KeyboardInterrupt usually happens because the user interrupted the program
  • ValueError happens when a value has the wrong form
  • RuntimeError happens when a program fails during execution for a different reason

So KeyboardInterrupt is usually about stopping a running script, not about invalid code.

If you are comparing exception types, you may also want to read about RuntimeError in Python.

Common causes #

The most common causes are:

  • Pressing Ctrl+C while a script is running
  • Manually stopping an infinite loop
  • Interrupting a long time.sleep() call
  • Stopping a script that is waiting for input or network activity

FAQ #

Is KeyboardInterrupt an error in my code? #

Usually no. It normally means the program was stopped by the user with Ctrl+C.

How do I stop KeyboardInterrupt from showing a traceback? #

Catch KeyboardInterrupt with try-except and print your own message before exiting.

try:
    while True:
        print("Running...")
except KeyboardInterrupt:
    print("\nStopped cleanly")

Does KeyboardInterrupt happen only in loops? #

No. It can happen during sleep, input, file work, or other long-running operations if you interrupt the program.

Should I always catch KeyboardInterrupt? #

Not always. Catch it when you want a clean shutdown or need to save data before exiting.

See also #

Press Esc to close