Handling SIGINT Signals in Python
In Python, you can respond to SIGINT signals (generated by pressing Ctrl C) by utilizing the signal.signal function. This function registers a handler function that will be executed when the specified signal is received. Here's an example demonstrating how to achieve the same functionality as the provided Perl code:
import signal import sys def signal_handler(sig, frame): print('You pressed Ctrl+C!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C') signal.pause()
In the above code:
This code provides an effective way to gracefully handle SIGINT signals in Python and perform cleanup actions before exiting the script.
The above is the detailed content of How Can I Gracefully Handle Ctrl C Interrupts (SIGINT) in Python?. For more information, please follow other related articles on the PHP Chinese website!