signal

Set handlers for asynchronous events

signal is a module that provides mechanisms to set handlers for asynchronous events.

Example

Using the alarm() function to limit the time a function can run; This is useful when you want to set a timeout. The following example sets an alarm for 5 seconds to excute a loop. If the loop takes more than 5 seconds, a TimeoutException is raised.

import signal

class TimeoutException(Exception):
    pass

def handler(signum, frame):
    signame = signal.Signals(signum).name
    print(f'Signal handler called with signal {signame} ({signum})')
    raise TimeoutException()

signal.signal(signal.SIGALRM, handler)
signal.alarm(5) # Set an alarm for 5 seconds

for i in range(10):
    print(i)
    time.sleep(1)

signal.alarm(0) # Disable the alarm

The following example sets an alarm for 5 seconds to excute func(). If func() takes more than 5 seconds, a TimeoutException is raised and the loop continues.

import signal

class TimeoutException(Exception):
    pass

def handler(signum, frame):
    signame = signal.Signals(signum).name
    print(f'Signal handler called with signal {signame} ({signum})')
    raise TimeoutException()

def func(i):
    print(i)
    time.sleep(i)

signal.signal(signal.SIGALRM, handler)

for i in range(10):
    signal.alarm(5) # Set an alarm for 5 seconds
    try:
        func(i)
    except TimeoutException:
        print('Timeout')
        continue
    else:
        print('Success')
        signal.alarm(0)

Last updated