Explaining Signal Module in Python
2 min readSep 21, 2022
The aim of this page📝 solve the following encounter in Python code
signal.signal(signal.SIGINT, termination.handler)
signal
is a built-in module and something like an "OS event listener"
…a means through which a program can receive information from the Operating System. When the operating system receives certain events, it can pass that to programs in the form of signals.
— Python Signal Module — What are Signals and How to Create Them? — AskPython
SIGNAL TYPES / SIGNIT EXAMPLE
- you can listen for a defined set of signals; some are OS-specific
- for example, press
CTRL + C
→ OS generates a signal → passes that to other programs - for this combination, the event
SIGINT
is generated and passed - on Win10, I am getting these 7 signals
>>> import signal3
>>> from pprint import pprint as pp
>>> pp(signal.valid_signals())
{<Signals.SIGINT: 2>,
<Signals.SIGILL: 4>,
<Signals.SIGFPE: 8>,
<Signals.SIGSEGV: 11>,
<Signals.SIGTERM: 15>,
<Signals.SIGBREAK: 21>,
<Signals.SIGABRT: 22>}
...INT
stands for interrupt; this is what the docs say about this particular one
signal.SIGINT
Interrupt from keyboard (CTRL + C).
Default action is to raise KeyboardInterrupt.
signal.SIGTERM
Termination signal.
SIGNAL HANDLER
- The original example contains 2 arguments to the
signal.signal()
statement, the other is a handler, i.e. a function that should be called upon the firing of the signal. - Note that
The handler is called with two arguments: the signal number (
signum
) and the current stack frame ( or aframe
object)
- …however, I am not explicly using these 2 args
- yet, the handler function call will fail without them
- Finally, the handler will do what needs to be done when e.g. ctrl+c is pressed
EXAMPLE
import signal
def termination_handler(signo, frame):
if input("~~> Interrupted ! Clean-up 'output.txt'? (y/N): ") == "y":
open("output.txt", "w").close()
exit("output deleted => bye")
else:
exit("output noT deleted => bye")
def main():
signal.signal(signal.SIGINT, termination_handler)
i = 0
while True:
i += 1
print(i)
with open("output.txt", "a") as f: f.write(str(i))
- In this particular example, the 🠉 has the same effect as catching the
KeyboardInterrupt
with atry/except
block - The 🠋 can contain a much smaller chunk of code, is, however, less economical/clean
def termination_handler():
if input("~~> Interrupted ! Clean-up 'output.txt'? (y/N): ") == "y":
open("output.txt", "w").close()
exit("output deleted => bye")
else:
exit("output noT deleted => bye")
def main(i=0):
try:
while True:
i += 1
print(i)
with open("output.txt", "a") as f: f.write(str(i))
except KeyboardInterrupt:
termination_handler()