How to get signal names from numbers in Python?

Python's signal module allows you to work with system signals, but getting signal names from their numeric values requires some introspection. You can create a mapping dictionary by examining the signal module's attributes and filtering for signal constants.

Creating a Signal Number to Name Mapping

The signal module contains all signal constants as attributes. We can iterate through these attributes to build a mapping ?

import signal

# Get all signal module attributes and create mapping
sig_items = reversed(sorted(signal.__dict__.items()))
signal_map = dict((k, v) for v, k in sig_items if v.startswith('SIG') and not v.startswith('SIG_'))

print("Signal number to name mapping:")
for signal_obj, name in signal_map.items():
    print(f"{signal_obj.value}: {name}")
Signal number to name mapping:
15: SIGTERM
11: SIGSEGV
2: SIGINT
4: SIGILL
8: SIGFPE
21: SIGBREAK
22: SIGABRT

Getting Signal Name by Number

Once you have the mapping, you can easily look up signal names by their numeric values ?

import signal

# Create signal mapping
sig_items = reversed(sorted(signal.__dict__.items()))
signal_map = dict((k, v) for v, k in sig_items if v.startswith('SIG') and not v.startswith('SIG_'))

def get_signal_name(signal_number):
    """Get signal name from signal number"""
    for signal_obj, name in signal_map.items():
        if signal_obj.value == signal_number:
            return name
    return f"Unknown signal: {signal_number}"

# Test with common signal numbers
test_signals = [2, 9, 15, 999]
for sig_num in test_signals:
    print(f"Signal {sig_num}: {get_signal_name(sig_num)}")
Signal 2: SIGINT
Signal 9: SIGKILL
Signal 15: SIGTERM
Signal 999: Unknown signal: 999

Alternative Approach Using signal.Signals

Python 3.5+ provides a more direct way using the signal.Signals enumeration ?

import signal

def get_signal_name_enum(signal_number):
    """Get signal name using signal.Signals enum"""
    try:
        return signal.Signals(signal_number).name
    except ValueError:
        return f"Unknown signal: {signal_number}"

# Test with various signal numbers
test_signals = [1, 2, 9, 15, 17]
print("Using signal.Signals enum:")
for sig_num in test_signals:
    print(f"Signal {sig_num}: {get_signal_name_enum(sig_num)}")
Using signal.Signals enum:
Signal 1: SIGHUP
Signal 2: SIGINT
Signal 9: SIGKILL
Signal 15: SIGTERM
Signal 17: SIGCHLD

Comparison of Methods

Method Python Version Pros Cons
Dictionary mapping All versions Works everywhere More complex setup
signal.Signals enum 3.5+ Simple and direct Modern Python only

Conclusion

Use signal.Signals(number).name for Python 3.5+ as it's the most straightforward approach. For older Python versions, create a dictionary mapping by filtering signal module attributes.

Updated on: 2026-03-24T20:47:08+05:30

616 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements