Signals in Python

Here’s the translation of the Go code to Python, formatted in Markdown suitable for Hugo:

Our program demonstrates how to handle Unix signals in Python. For example, we might want a server to gracefully shutdown when it receives a SIGTERM, or a command-line tool to stop processing input if it receives a SIGINT. Here’s how to handle signals in Python.

import signal
import sys

def signal_handler(sig, frame):
    print()
    print(sig)
    sys.exit(0)

if __name__ == "__main__":
    # Register the signal handler
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    print("awaiting signal")
    # This keeps the program running until a signal is received
    signal.pause()

Python’s signal handling works by registering a function to be called when a signal is received. We create a signal_handler function that will be called when a signal is received.

We use signal.signal() to register our handler for both SIGINT and SIGTERM signals.

The signal.pause() function suspends execution of the program until a signal is received. This is equivalent to the main goroutine waiting on a channel in the original example.

When we run this program it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal, causing the program to print the signal number and then exit.

$ python signals.py
awaiting signal
^C
2

In this output, 2 is the signal number for SIGINT.

Python’s signal handling is somewhat different from the original example. Instead of using channels, Python uses callback functions. However, the core concept of responding to Unix signals remains the same.

Note that on Windows, signal handling works differently and some signals (like SIGTERM) may not be available.