How to capture sigint in Python?

Estimated read time 2 min read

In Python, you can capture the SIGINT (KeyboardInterrupt) signal using the signal module. This module provides functions for handling various signals, including SIGINT. Here’s an example of how you can capture the SIGINT signal and perform custom actions when it occurs:

import signal
import sys

def signal_handler(sig, frame):
    # Custom action to perform when SIGINT is received
    print("SIGINT received. Cleaning up...")
    # Perform any cleanup operations here, if needed
    # ...

    # Exit the program
    sys.exit(0)

# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)

# Your main program code goes here

# Run an infinite loop to keep the program running
while True:
    # Your program logic here
    # ...

    # Allow the program to be interrupted by signals
    signal.pause()

In this example, the signal_handler function is defined to handle the SIGINT signal. It prints a message and performs any necessary cleanup operations before exiting the program. The signal.signal function is used to register the signal handler for SIGINT.

The program then enters an infinite loop using while True, where your main program logic can be placed. The signal.pause() function is called to allow the program to be interrupted by signals. This function causes the program to block until a signal is received, at which point the registered signal handler (signal_handler) is executed.

When you run this code, pressing Ctrl+C will generate the SIGINT signal, which will be captured by the signal handler, and the custom actions defined in signal_handler will be executed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply