KeyboardInterrupt
PythonINFONotableControl FlowHIGH confidence

User pressed Ctrl+C

What this means

Raised when the user hits the interrupt key, which is normally `Ctrl+C`. This is a common way for a user to intentionally terminate a long-running script.

Why it happens
  1. 1The user pressing `Ctrl+C` in the terminal where the script is running.
  2. 2An integrated development environment (IDE) sending an interrupt signal to the running process.
  3. 3An automated script sending a `SIGINT` signal to the process.
How to reproduce

This exception is raised when the user interrupts the execution of the program, for example, during a `time.sleep()` call.

trigger — this will error
trigger — this will error
import time
print("Program running... Press Ctrl+C to exit.")
try:
    time.sleep(10) # Program waits here
except KeyboardInterrupt:
    print("
Program interrupted by user.")

expected output

Program running... Press Ctrl+C to exit.
^C
Program interrupted by user.

Fix 1

Use `try...except` to perform cleanup

WHEN You need to perform a cleanup action when the user aborts the script.

Use `try...except` to perform cleanup
try:
    while True:
        # Main application loop
        pass
except KeyboardInterrupt:
    print("Exiting gracefully...")
    # e.g., save data, close connections

Why this works

By wrapping the main loop in a `try...except KeyboardInterrupt` block, you can catch the user's interrupt signal and execute cleanup code before the program exits.

Fix 2

Use `try...finally` for guaranteed cleanup

WHEN Cleanup must happen regardless of whether the program was interrupted or exited normally.

Use `try...finally` for guaranteed cleanup
f = open("my_file.txt", "w")
try:
    # Write to file in a loop
    while True:
        f.write("data
")
finally:
    print("Closing file.")
    f.close()

Why this works

The `finally` block is guaranteed to execute when the `try` block is exited for any reason, including a `KeyboardInterrupt`, ensuring critical resources are released.

Code examples
Triggerpython
import time
time.sleep(60)  # press Ctrl+C → KeyboardInterrupt
Handle with try/exceptpython
try:
    run_long_job()
except KeyboardInterrupt:
    print("\nInterrupted — saving state...")
    save_checkpoint()
Avoid abrupt termination with signalpython
import signal, sys

def graceful_exit(sig, frame):
    print("Shutting down...")
    cleanup()
    sys.exit(0)

signal.signal(signal.SIGINT, graceful_exit)
What not to do

Catching `KeyboardInterrupt` and not exiting the program

The user's intent when pressing `Ctrl+C` is to stop the program. Ignoring this signal and continuing to run is unexpected and frustrating for the user.

Sources
Official documentation ↗

cpython/Python/pythonrun.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors