×

注意!页面内容来自https://runebook.dev/en/docs/python/library/exceptions/KeyboardInterrupt,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页



Stop Right There: Understanding Python's KeyboardInterrupt Exception

2025-10-23

The KeyboardInterrupt exception is raised when the user interrupts the execution of a programtypically by pressing a combination of keys like Ctrl+C (Control-C) on a terminal or command prompt.

It is one of Python's Built-in Exceptionsmeaning you don't need to import anything special to use or catch it.

This exception is the standard way to signal a running Python script to stop immediately and is generally considered a graceful way to terminate a programunlikesaykilling the process externally.

While KeyboardInterrupt is straightforwarda few common issues and "traps" pop up

A common mistake is using a bare except or catching KeyboardInterrupt too generally and doing nothingwhich can make it impossible to stop the program.

Common TroubleExplanation
Silent CatchCatching KeyboardInterrupt and not re-raising it or exiting can make your program unresponsive to Ctrl+C. The user will think the program is frozen.
Bare exceptUsing except: without specifying the exception also catches KeyboardInterrupt (and SystemExit)which is usually bad practice as it hides unexpected errors and control signals.

This code will run forever and pressing Ctrl+C won't stop it because the exception is caught and ignored.

import time

print("Press Ctrl+C to stop (or so you think!)")
try:
    while True:
        # Some critical operation
        print("Working...")
        time.sleep(1)
#  This catches KeyboardInterrupt and prevents the program from stopping.
except Exception:
    pass 
# The program will silently continue forever!

If you need to catch it for cleanup but still want the program to terminateyou should re-raise the exception or explicitly exit.

import time
import sys

print("Press Ctrl+C to stop.")
try:
    while True:
        print("Working...")
        time.sleep(1)
except KeyboardInterrupt:
    print("\n Interruption detected! Performing cleanup...")
    # Clean up resources (close filesdisconnect from networksetc.)
    # ...
    print("Cleanup complete. Exiting gracefully.")
    # Use sys.exit() or just let the block end to terminate
    sys.exit(0) # Explicitly exit the program

Some operations performed by external C/C++ libraries or system calls (like certain I/O operations or tight computations) might be not immediately interruptible.

Common TroubleExplanation
C-Extension BlocksWhen Python code calls into C-level codethe C code runs without checking for Python's interrupts until it returns control to the Python interpreter. A long-running C function might seem to ignore Ctrl+C.

There isn't a direct Python solution for thisas it's a limitation of the external code. Howeverwhen using librarieslook for timeouts or non-blocking modes as alternatives. For code you controlensure you return to Python frequently.

The best practice is to use KeyboardInterrupt to trigger a graceful shutdown. This means catching the interruptperforming necessary cleanupand then exitingensuring data integrity.

This example shows how to use a try...except block to ensure cleanup code runs before the program terminates.

import time
import os

# Imagine this is a resource we need to closelike a file handle or a database connection
def open_resource():
    print(" Resource acquired (e.g.file opened).")
    return "DB_CONNECTION_OBJECT"

def close_resource(resource):
    print(f" Closing resource: {resource}...")
    # Add actual closing logic here
    print("Resource released.")

# Main program loop
def run_program():
    resource = None
    try:
        resource = open_resource()
        print("Starting main loop. Press Ctrl+C to initiate graceful shutdown.")
        
        # Loop that does the main work
        while True:
            # Simulate work
            print("Working and saving progress...")
            time.sleep(2)
            
    #  This is where we catch the user interrupt!
    except KeyboardInterrupt:
        print("\n\n*** Keyboard Interrupt Detected! ***")
        
    finally:
        #  The 'finally' block ensures cleanup runs whether an exception occurred or not!
        if resource:
            close_resource(resource)
        
        print("Program finished gracefully.")

if __name__ == "__main__":
    run_program()

python



Beyond askdirectory(): Deep Dive into Tkinter's dirs_select_event for Advanced GUI

The method dirs_select_event(event) is part of the FileDialog classand it's designed to be the event handler that is called when a user single-clicks on a directory in the file selection list of a custom-created file dialog


Python urllib.request: Troubleshooting BaseHandler.parent and Delegation

Here's a friendly explanation of BaseHandler. parentcommon issuesand alternative approaches.In Python's urllib. request


Avoiding Pitfalls with PyLong_CheckExact(): A Friendly Guide to Integer Type Checking

The C function PyLong_CheckExact(op) is part of the Python/C APIspecifically designed for extension modules or when embedding Python in a C application



Sustainable Living: Small ChangesBig Impact

The tarfile. TarInfo. type attribute holds a single-character string that indicates the type of file represented by the TarInfo object


From Node to Value: Understanding and Replacing getAttributeNodeNS()

The method xml. dom. Element. getAttributeNodeNS() is part of Python's built-in xml. dom modulewhich implements the Document Object Model (DOM) standard


Stop Using os.times()! Modern Python Clocks for Performance Measurement

The user asked about time. asctime()but oftenwhen discussing OS-level timing and performanceprogrammers might be thinking about os


Ditching dbm.ndbm.close(): The Power of 'with' and 'shelve' for Key-Value Stores

Let's dive into dbm. ndbm. ndbm. close() in Python.The module dbm. ndbm provides an interface to the traditional Unix ndbm library


Handling ExternalClashError: Best Practices for Python's mailbox.MMDF.lock()

Here's a friendly guide to common issues and alternatives for mailbox. MMDF. lock().The lock() method in a mailbox class like mailbox


Beyond the Basics of shutil.move(): Handling Overwrites and Cross-Filesystem Operations

Here's a friendly breakdown of common issues and some alternative approaches with sample code!The shutil. move(srcdst) function is Python's high-level way to move files or directories


The Signal Mask: A Deep Dive into Python's signal.SIG_BLOCK

Here is a friendlydetailed explanation covering common issues and alternative methodscomplete with sample code.The signal