Explaining Signal Module in Python

signal.signal(signal.SIGINT, termination.handler)

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>}
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
  • 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))
  • 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()

LINKS

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

63 Followers

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com