User pressed Ctrl+C
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.
- 1The user pressing `Ctrl+C` in the terminal where the script is running.
- 2An integrated development environment (IDE) sending an interrupt signal to the running process.
- 3An automated script sending a `SIGINT` signal to the process.
This exception is raised when the user interrupts the execution of the program, for example, during a `time.sleep()` call.
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.
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.
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.
import time time.sleep(60) # press Ctrl+C → KeyboardInterrupt
try:
run_long_job()
except KeyboardInterrupt:
print("\nInterrupted — saving state...")
save_checkpoint()import signal, sys
def graceful_exit(sig, frame):
print("Shutting down...")
cleanup()
sys.exit(0)
signal.signal(signal.SIGINT, graceful_exit)✕ 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.
cpython/Python/pythonrun.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev