python signal_error ai_generated true

KeyboardInterrupt

ID: python/keyboardinterrupt

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

User pressed Ctrl+C. Program interrupted. Handle with signal or try/except for graceful shutdown.

generic

Workarounds

  1. 95% success Add cleanup code: try/finally or atexit for graceful shutdown
    try:
        main()
    except KeyboardInterrupt:
        print('\nShutting down...')
        cleanup()

    Sources: https://docs.python.org/3/library/atexit.html

  2. 88% success Use signal.signal(signal.SIGINT, handler) for custom interrupt handling
    signal.SIGINT, handler

    Sources: https://docs.python.org/3/library/signal.html

Dead Ends

Common approaches that don't work:

  1. Catch and ignore KeyboardInterrupt 80% fail

    User can't stop the program — bad UX

Error Chain

Frequently confused with: