Python signal Module
Example
Handle keyboard interrupt (Ctrl+C):
import signal
import sys
def handler(signum, frame):
print('Signal received, exiting gracefully...')
sys.exit(0)
signal.signal(signal.SIGINT, handler)
print('Press Ctrl+C to trigger signal')
Try it Yourself »
Definition and Usage
The signal module provides mechanisms to handle asynchronous events and signals from the operating system.
Use it to handle interrupts, timeouts, or other OS signals, allowing your program to respond to system events gracefully.
Members
Member | Description |
---|---|
alarm() | Schedule a SIGALRM signal after specified seconds (Unix). |
default_int_handler() | Default handler for SIGINT (raises KeyboardInterrupt). |
getsignal() | Return the current signal handler for a signal. |
pause() | Wait for a signal to arrive (Unix). |
raise_signal() | Send a signal to the calling process. |
set_wakeup_fd() | Set a file descriptor to wake up on signals. |
signal() | Set a handler for a specific signal. |
SIGABRT | Signal for abort. |
SIGALRM | Signal for alarm clock (Unix). |
SIGINT | Signal for interrupt (Ctrl+C). |
SIGTERM | Signal for termination request. |