When working with Python scripts that execute multiple processes and database connections, a graceful exit upon receiving a SIGINT (Ctrl C) interruption is often desirable. In this instance, it becomes necessary to register a handler for SIGINT to perform necessary cleanup tasks.
To achieve the analogue of Perl's SIGINT handling in Python, leverage the signal.signal function as follows:
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()
The above is the detailed content of How to Gracefully Handle SIGINT Interruptions in Python?. For more information, please follow other related articles on the PHP Chinese website!