Python Glossary Русский

all Python 3Linux · macOSsignalfunction

signal.alarm()

timers

Asks the OS to deliver SIGALRM after a whole number of seconds; alarm(0) cancels it. Unix only (Linux, macOS).

Syntax

remaining = signal.alarm(seconds)

There is one alarm per process: a new call cancels the previous one and returns how many seconds it had left — two libraries using alarm break each other. Without a handler of your own SIGALRM simply kills the process. The resolution is whole seconds; use setitimer for fractions. Put the alarm(0) cancel in finally: a forgotten alarm fires in the middle of unrelated code.

Examples

import signal
print(signal.alarm(5))  # → 0 — будильника не было
print(signal.alarm(0))  # → 5 — отменили, оставалось 5 с
import signal
def on_alarm(signum, frame):
    raise TimeoutError('слишком долго')
old = signal.signal(signal.SIGALRM, on_alarm)
signal.alarm(1)
try:
    print(sum(range(1000)))  # → 499500 — успели до будильника
finally:
    signal.alarm(0)
    signal.signal(signal.SIGALRM, old)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy