- Модуль signal в Python
- Что такое сигнал?
- Что такое обработчик сигналов в Python?
- Использование SIGALARM
- Модуль signal в Python, создание обработчиков сигналов.
- Основные правила.
- Выполнение обработчиков сигналов Python.
- Сигналы и потоки.
- Примеры:
- блог JOHN_16
- четверг, 28 февраля 2013 г.
- Python: модуль signal. Перевод документации. Примеры.
- signal — Set handlers for asynchronous events¶
- General rulesВ¶
- Execution of Python signal handlersВ¶
- Signals and threadsВ¶
- Module contentsВ¶
- ExampleВ¶
- Note on SIGPIPEВ¶
Модуль signal в Python
В этой статье мы рассмотрим использование модуля Python signal. Этот модуль очень полезен, когда мы хотим обрабатывать определенные сигналы с помощью Python.
Что такое сигнал?
Сигнал — это средство, с помощью которого программа может получать информацию от операционной системы. Когда операционная система получает определенные события, она может передать их программам в виде сигналов.
Например, когда мы нажимаем клавиши Ctrl + C на клавиатуре, операционная система генерирует сигнал и передает его программам. Для этой конкретной комбинации генерируется сигнал SIGINT и передается в программы.
Для всех распространенных операционных систем существует стандартный шаблон для назначения этих сигналов, которые обычно являются сокращением от целых чисел.
В Python эти сигналы определены в модуле signal .
Чтобы просмотреть все допустимые сигналы в вашей системе (в зависимости от ОС), вы можете использовать signals.valid_signals()
Теперь для всех сигналов есть некоторые действия по умолчанию, которые ОС назначит каждой программе. Если вместо этого мы хотим иметь другое поведение, мы можем использовать обработчики сигналов.
Что такое обработчик сигналов в Python?
Обработчик сигналов в Python — это определяемая пользователем функция, с помощью которой можно обрабатывать сигналы Python.
Если мы возьмем сигнал SIGINT (сигнал прерывания), поведение по умолчанию будет заключаться в остановке текущей запущенной программы.
Однако мы можем назначить обработчик сигнала для обнаружения этого сигнала и вместо этого выполнять нашу собственную обработку.
Давайте посмотрим, как это сделать.
После того, как мы запустим нашу программу, когда мы нажмем Ctrl + C, программа перейдет к функции signal_handler() , поскольку мы зарегистрировали обработчик с помощью SIGINT (Ctrl + C).
У нас также есть другой обработчик exit_handler() который выходит из программы, если мы нажимаем Ctrl + Z, который отправляет сигнал SIGTSTP .
Здесь я нажал Ctrl + C, чтобы перейти к функции signal_handler() , а затем нажал Ctrl + Z, чтобы выйти из программы.
Обратите внимание, что есть объект frame стека ( frame ) для отслеживания стека выполнения основной программы.
Использование SIGALARM
Мы можем использовать сигнал SIGALARM для отправки сигналов тревоги нашей программе. Напишем простой обработчик сигнала.
В последней строке мы ждем в течение достаточного времени (6 секунд), чтобы сигнал тревоги прошел в нашу программу. В противном случае, поскольку программа завершилась бы, сигнал не будет получен.
Модуль signal в Python, создание обработчиков сигналов.
Модуль signal предоставляет механизмы для использования обработчиков сигналов в Python.
Сигналы — это функция операционной системы, которая позволяет уведомлять программу о событии и обрабатывать его асинхронно. Они могут быть созданы самой системой или отправлены из одного процесса в другой. Поскольку сигналы прерывают регулярный поток программы, возможно, что некоторые операции, особенно ввод/вывод, могут привести к ошибкам, если сигнал принимается посередине.
Как и в других формах программирования, основанного на событиях, сигналы принимаются путем создания функции обратного вызова, называемой обработчиком сигнала, которая вызывается при возникновении сигнала. Аргументами обработчика сигнала являются номер сигнала и кадр стека от точки в программе, которая была прервана сигналом.
Основные правила.
Функция signal.signal() позволяет определять пользовательские обработчики, которые будут выполняться при получении сигнала. Установлено небольшое количество обработчиков по умолчанию: signal.SIGPIPE игнорируется, поэтому об ошибках записи в каналах и сокетах можно сообщать как обычные исключения Python, а signal.SIGINT преобразуется в исключение KeyboardInterrupt , если родительский процесс не изменил его.
Обработчик определенного сигнала после его установки остается до тех пор, пока он не будет сброшен явным образом, за исключением обработчика для signal.SIGCHLD , который следует за базовой реализацией.
Выполнение обработчиков сигналов Python.
Обработчик сигналов Python не выполняется внутри обработчика сигналов низкого уровня (C). Вместо него, низкоуровневый обработчик сигнала устанавливает флаг, который указывает виртуальной машине выполнить соответствующий обработчик сигнала Python на более позднем этапе, например при следующей инструкции байт-кода.
Это имеет последствия:
- Не имеет смысла отлавливать синхронные ошибки, такие как signal.SIGFPE или signal.SIGSEGV , которые вызваны недопустимой операцией в C-коде. Python вернется из обработчика сигнала к коду C, который, вероятно, снова вызовет тот же сигнал, что приведет к зависанию Python. Начиная с Python 3.3 можно использовать модуль обработчика ошибок, чтобы сообщать о синхронных ошибках.
- Долгосрочные вычисления, реализованные исключительно на языке C, например сопоставление регулярных выражений для большого объема текста, могут выполняться непрерывно в течение произвольного промежутка времени, независимо от полученных сигналов. Обработчики сигналов Python будут вызваны после завершения расчета.
Сигналы и потоки.
Обработчики сигналов Python всегда выполняются в основном потоке Python, даже если сигнал был получен в другом потоке. Это означает, что сигналы не могут использоваться в качестве средства связи между потоками. Вместо этого вы можете использовать примитивы синхронизации из модуля threading .
Кроме того, только основной поток может устанавливать новый обработчик сигнала.
Примечание:
- Программирование с обработчиками сигналов Unix — это нетривиальное занятие. Существует некоторая степень стандартизации между версиями Unix, но есть и некоторые различия, поэтому, если возникают какие-то проблемы, необходимо сразу обратиться к документации по операционной системе.
Примеры:
Пример программы, которая использует функцию OS signal.alarm() , чтобы ограничить время ожидания открытия файла. Такое поведение полезно, если файл предназначен для последовательного устройства, которое может не включаться, что приводит к зависанию функции os.open() на неопределенное время. Решение состоит в том, чтобы установить 5-секундную тревогу перед открытием файла. Если операция занимает слишком много времени, сигнал тревоги будет отправлен, и обработчик вызывает исключение.
Передача выходных данных программы на такие инструменты, как head(1) , приведет к отправке сигнала signal.SIGPIPE вашему процессу, когда приемник стандартного выхода закроется раньше. Это приводит к исключению, подобному BrokenPipeError: [Errno 32] Broken pipe . Чтобы поймать это исключение, оберните точку входа следующим образом:
Не устанавливайте SIGPIPE в SIG_DFL, чтобы избежать исключения BrokenPipeError . Это может привести к неожиданному завершению работы программы, также при каждом прерывании любого соединения с сокетом, когда программа все еще выполняет запись в него.
блог JOHN_16
Здесь я планирую размещать небольшие статьи на интересующие меня темы.
четверг, 28 февраля 2013 г.
Python: модуль signal. Перевод документации. Примеры.
Модуль предоставляет механизм использования обработчиков сигналов. Некоторые общие правила для работ с сигналами и их обработчиками:
- Обработчик для конкретного сигнала, однажды установленный, остается таковым пока не будет явного сброса (Python эмулирует интерфейс в стиле BSD, независимо от конкретной реализации), за исключением обработчика для SIGCHLD, который следует за базовой реализации.
- Не существует способа временно «заблокировать» сигналы от критических секций (так как это не поддерживается для всех разновидностей Unix).
- Хотя обработчики сигналов в Python вызываются асинхронно, в этом заинтересован пользователь Python, они могут проявиться только между атомарными инструкциями интерпретатора Python. Это означает что сигналы поступившие во время длительных вычислительным реализаций на чистом C (такие как поиск совпадение регулярного выражения в большом фрагменте текста) могут быть отложены на произвольное количество времени.
- Когда сигнал прибывает во время выполнения операций ввода/вывода, то ими возможно возбуждение исключительных ситуаций после возвращения обработчиков сигналов. Это зависит от базовой семантики UNIX подобных систем относительно прерванных системных вызовов.
- Поскольку обработчик сигнала в C всегда возвращается, вряд ли имеет смысл ловить синхронные ошибки такие как SIGFPE или SIGSEGV.
- Python устанавливает небольшое количество обработчиков сигналов по умолчанию: SIGPIPE игнорируется (так ошибки записи на каналах и сокетах могут быть представлены как обычные Python исключения) и SIGINT транслируется в KeyboardInterrupt исключение. Все они могут быть переопределены.
- Некоторое внимание должно быть уделено если сигналы и потоки используется вместе в одной программе. Основное что нужно запомнить при одновременном использовании сигналов и потоков: всегда выполнять операции signal() в основном потоке выполнения. Любой поток может выполнять alarm(), getsignal(), pause(), settimer(), gettimer(); только главный поток может устанавливать новые обработчики сигналов и он же единственный кто может получать сигналы (это обеспечивается модулем signal, даже если базовая реализация потоков поддерживает посылку сигналов индивидуальным потокам). Это означает что сигналы не могут быть использованы для межпотокового сообщения. Используйте блокировки вместо этого.
Переменные определенные в модуле:
Сигнал сообщает о нажатии клавиши CTRL+C. Этот сигнал может использоваться только с os.kill() .
Доступно только на Windows OS
Новое в версии 2.7
Сигнал сообщает о нажатии клавиши CTRL+BREAK. Этот сигнал может использоваться только с os.kill() .
Доступно только на Windows OS
Новое в версии 2.7
Модуль определяет следующие функции:
Устанавливает передаваемый временной таймер( один из signal.ITIMER_REAL , signal.ITIMER_VIRTUAL , signal.ITIMER_PROF ) указанный в which на активацию через seconds (примимаемое значение вещественное float, в отличии от alarm() ) и каждые interval секунд после этого. Таймер может быть стерт если передать 0 в seconds.
Когда таймер срабатывает сигнал посылается процессу. Посылаемый сигнал завист от таймера который используется; signal.ITIMER_REAL будет посылать SIGALRM, signal.ITIMER_VIRTUAL посылает SIGVTALRM, signal.ITIMER_PROF будет посылать SIGPROF.
Старые значения возвращаются в виде кортежа (задержка, интервал).
Попытка передачи недествительного значения интерала таймера вызовет исключение ItimerError. Доступно в UNIX.
Новое в Python 2.6
Возвращает текущее значение заданного временного таймера which. Доступно в UNIX.
Новое в Python 2.6
Установить пробуждающий файловый дескриптор в fd. Когда процесс получает сигнал ‘\0’ байт записывается в файловый дескриптор. Это может быть использованно библиотекой для пробуждения опрашивающего или выбираюшего вызова, позволяющего сигналу быть полностью обработанным.
Старый пробуждающий файловый дескриптор возвращается. fd должен быть не блокирующий. Это должно быть до библиотеки, что бы удалить все байты перед очередным вызовом.
В случае многопоточности эта функция может быть вызвана толкьо из основного потока; попытка вызова из других потоков вызовет исключение ValueError.
Новое в версии 2.6
Изменяет поведение системного вызова перезапуска: если flag равен False системные вызовы будут перезапущены когда произойдет прерывание сигналом signalnum, в противном случае системные вызовы будут прерваны. Ничего не возвращает. Доступно в UNIX (смотри man страницу siginterrupt(3)).
Помните что устанавливая обработчик сигнала используя signal() будет сброшено поведение перезапуска на прерывающее неявным вызовом siginterrupt() c истинным значением flag для данного сигнала.
Новое в версии Python 2.6
Устанавливает обработчик для сигнала signalnum функцию handler, которая может быть вызываемым объектом Python принимающее два аргумента или одним из специальных значений: signal.SIG_IGN , signal.SIG_DFL . Возращает предыдущий обработчик сигнала. (Смотри man страницу signa(2)).
В случае многопоточности эта функция может быть вызвана только из основного потока; попытка вызова из других потоков вызовет исключение ValueError.
handler вызывается с двумя аргументами: номером сигнала и текущим фреймом стэка (None или объект фрейма, смотри модуль inspect и модель данных Python).
На Windows signal() может быть вызван только с значениями SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, в противном случае будет возбуждено исключение ValueError.
#-*- coding: utf-8 -*-
import signal, sys, time
def handle(signum, frame):
print ‘Alarm! job failed’
sys.exit(1)
def job(n):
data=[]
for x in xrange(n):
data.append(x**2)
time.sleep(0.1)
# Имитация простой работы, которая будет выполнена успешно
signal.alarm(3)
job(10)
print ‘Job 1 done’
signal.alarm(0)
# Имитация объемной работы, которая не будет успешно выполнена
signal.alarm(3)
job(100)
print ‘Job 2 done’
signal.alarm(0)
#-*- coding: utf-8 -*-
import signal, time, datetime
class Signal_handler(object):
«»» Класс обрабатывающий системные сигналы «»»
def __init__(self, target):
«»»target — экземпляр класса»»»
self.target=target
def handle_sigalarm(self, signum, frame):
self.target.process_alarm_signal()
def __init__(self, *args, **kwargs):
# Регистрируем обработчики сигналов
sh=Signal_handler(self)
signal.signal(signal.SIGALRM, sh.handle_sigalarm)
# Устанавливаем таймер
signal.setitimer(signal.ITIMER_REAL, 3, 3)
def process_alarm_signal(self):
print ‘<> — alarm_checking’ .format(datetime.datetime.now())
if (datetime.datetime.now()-self.datetime_mark).seconds>=10:
# устанавливаем переменную для выхода из цикла
self.need_break=True
# отключаем таймер
signal.setitimer(signal.ITIMER_REAL, 0)
def run(self):
self.need_break=False
self.datetime_mark=datetime.datetime.now()
print ‘<> — Run’ .format(datetime.datetime.now())
while not self.need_break:
# симуляция работы
time.sleep(1)
if __name__== ‘__main__’ :
foo=Foo()
foo.run()
#-*- coding: utf-8 -*-
import signal, time, datetime
signal — Set handlers for asynchronous events¶
This module provides mechanisms to use signal handlers in Python.
General rulesВ¶
The signal.signal() function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception if the parent process has not changed it.
A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for SIGCHLD , which follows the underlying implementation.
Execution of Python signal handlersВ¶
A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point(for example at the next bytecode instruction). This has consequences:
It makes little sense to catch synchronous errors like SIGFPE or SIGSEGV that are caused by an invalid operation in C code. Python will return from the signal handler to the C code, which is likely to raise the same signal again, causing Python to apparently hang. From Python 3.3 onwards, you can use the faulthandler module to report on synchronous errors.
A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.
Signals and threadsВ¶
Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.
Besides, only the main thread of the main interpreter is allowed to set a new signal handler.
Module contentsВ¶
Changed in version 3.5: signal (SIG*), handler ( SIG_DFL , SIG_IGN ) and sigmask ( SIG_BLOCK , SIG_UNBLOCK , SIG_SETMASK ) related constants listed below were turned into enums . getsignal() , pthread_sigmask() , sigpending() and sigwait() functions return human-readable enums .
The variables defined in the signal module are:
This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it.
This is another standard signal handler, which will simply ignore the given signal.
Interrupt from keyboard (CTRL + BREAK).
Bus error (bad memory access).
Child process stopped or terminated.
Continue the process if it is currently stopped
Floating-point exception. For example, division by zero.
ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
Hangup detected on controlling terminal or death of controlling process.
Interrupt from keyboard (CTRL + C).
Default action is to raise KeyboardInterrupt .
It cannot be caught, blocked, or ignored.
Broken pipe: write to pipe with no readers.
Default action is to ignore the signal.
Segmentation fault: invalid memory reference.
User-defined signal 1.
User-defined signal 2.
Window resize signal.
All the signal numbers are defined symbolically. For example, the hangup signal is defined as signal.SIGHUP ; the variable names are identical to the names used in C programs, as found in . The Unix man page for †signal() ’ lists the existing signals (on some systems this is signal(2), on others the list is in signal(7)). Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module.
The signal corresponding to the Ctrl+C keystroke event. This signal can only be used with os.kill() .
New in version 3.2.
The signal corresponding to the Ctrl+Break keystroke event. This signal can only be used with os.kill() .
New in version 3.2.
One more than the number of the highest signal number.
Decrements interval timer in real time, and delivers SIGALRM upon expiration.
Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration.
Decrements interval timer both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration.
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked.
New in version 3.3.
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked.
New in version 3.3.
A possible value for the how parameter to pthread_sigmask() indicating that the signal mask is to be replaced.
New in version 3.3.
The signal module defines one exception:
exception signal. ItimerError В¶
Raised to signal an error from the underlying setitimer() or getitimer() implementation. Expect this error if an invalid interval timer or a negative time is passed to setitimer() . This error is a subtype of OSError .
New in version 3.3: This error used to be a subtype of IOError , which is now an alias of OSError .
The signal module defines the following functions:
signal. alarm ( time ) В¶
If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled.
Availability : Unix. See the man page alarm(2) for further information.
signal. getsignal ( signalnum ) В¶
Return the current signal handler for the signal signalnum. The returned value may be a callable Python object, or one of the special values signal.SIG_IGN , signal.SIG_DFL or None . Here, signal.SIG_IGN means that the signal was previously ignored, signal.SIG_DFL means that the default way of handling the signal was previously in use, and None means that the previous signal handler was not installed from Python.
signal. strsignal ( signalnum ) В¶
Return the system description of the signal signalnum, such as “Interrupt”, “Segmentation fault”, etc. Returns None if the signal is not recognized.
New in version 3.8.
Return the set of valid signal numbers on this platform. This can be less than range(1, NSIG) if some signals are reserved by the system for internal use.
New in version 3.8.
Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing.
Availability : Unix. See the man page signal(2) for further information.
signal. raise_signal ( signum ) В¶
Sends a signal to the calling process. Returns nothing.
New in version 3.8.
Send signal sig to the process referred to by file descriptor pidfd. Python does not currently support the siginfo parameter; it must be None . The flags argument is provided for future extensions; no flag values are currently defined.
See the pidfd_send_signal(2) man page for more information.
New in version 3.9.
Send the signal signalnum to the thread thread_id, another thread in the same process as the caller. The target thread can be executing any code (Python or not). However, if the target thread is executing the Python interpreter, the Python signal handlers will be executed by the main thread of the main interpreter . Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with InterruptedError .
Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id.
If signalnum is 0, then no signal is sent, but error checking is still performed; this can be used to check if the target thread is still running.
Raises an auditing event signal.pthread_kill with arguments thread_id , signalnum .
Availability : Unix. See the man page pthread_kill(3) for further information.
New in version 3.3.
Fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller. Return the old signal mask as a set of signals.
The behavior of the call is dependent on the value of how, as follows.
SIG_BLOCK : The set of blocked signals is the union of the current set and the mask argument.
SIG_UNBLOCK : The signals in mask are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked.
SIG_SETMASK : The set of blocked signals is set to the mask argument.
mask is a set of signal numbers (e.g.
For example, signal.pthread_sigmask(signal.SIG_BLOCK, []) reads the signal mask of the calling thread.
SIGKILL and SIGSTOP cannot be blocked.
New in version 3.3.
Sets given interval timer (one of signal.ITIMER_REAL , signal.ITIMER_VIRTUAL or signal.ITIMER_PROF ) specified by which to fire after seconds (float is accepted, different from alarm() ) and after that every interval seconds (if interval is non-zero). The interval timer specified by which can be cleared by setting seconds to zero.
When an interval timer fires, a signal is sent to the process. The signal sent is dependent on the timer being used; signal.ITIMER_REAL will deliver SIGALRM , signal.ITIMER_VIRTUAL sends SIGVTALRM , and signal.ITIMER_PROF will deliver SIGPROF .
The old values are returned as a tuple: (delay, interval).
Attempting to pass an invalid interval timer will cause an ItimerError .
signal. getitimer ( which ) В¶
Returns current value of a given interval timer specified by which.
signal. set_wakeup_fd ( fd, *, warn_on_full_buffer=True ) В¶
Set the wakeup file descriptor to fd. When a signal is received, the signal number is written as a single byte into the fd. This can be used by a library to wakeup a poll or select call, allowing the signal to be fully processed.
The old wakeup fd is returned (or -1 if file descriptor wakeup was not enabled). If fd is -1, file descriptor wakeup is disabled. If not -1, fd must be non-blocking. It is up to the library to remove any bytes from fd before calling poll or select again.
When threads are enabled, this function can only be called from the main thread of the main interpreter ; attempting to call it from other threads will cause a ValueError exception to be raised.
There are two common ways to use this function. In both approaches, you use the fd to wake up when a signal arrives, but then they differ in how they determine which signal or signals have arrived.
In the first approach, we read the data out of the fd’s buffer, and the byte values give you the signal numbers. This is simple, but in rare cases it can run into a problem: generally the fd will have a limited amount of buffer space, and if too many signals arrive too quickly, then the buffer may become full, and some signals may be lost. If you use this approach, then you should set warn_on_full_buffer=True , which will at least cause a warning to be printed to stderr when signals are lost.
In the second approach, we use the wakeup fd only for wakeups, and ignore the actual byte values. In this case, all we care about is whether the fd’s buffer is empty or non-empty; a full buffer doesn’t indicate a problem at all. If you use this approach, then you should set warn_on_full_buffer=False , so that your users are not confused by spurious warning messages.
Changed in version 3.5: On Windows, the function now also supports socket handles.
Changed in version 3.7: Added warn_on_full_buffer parameter.
Change system call restart behaviour: if flag is False , system calls will be restarted when interrupted by signal signalnum, otherwise system calls will be interrupted. Returns nothing.
Availability : Unix. See the man page siginterrupt(3) for further information.
Note that installing a signal handler with signal() will reset the restart behaviour to interruptible by implicitly calling siginterrupt() with a true flag value for the given signal.
signal. signal ( signalnum, handler ) В¶
Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL . The previous signal handler will be returned (see the description of getsignal() above). (See the Unix man page signal(2) for further information.)
When threads are enabled, this function can only be called from the main thread of the main interpreter ; attempting to call it from other threads will cause a ValueError exception to be raised.
The handler is called with two arguments: the signal number and the current stack frame ( None or a frame object; for a description of frame objects, see the description in the type hierarchy or see the attribute descriptions in the inspect module).
On Windows, signal() can only be called with SIGABRT , SIGFPE , SIGILL , SIGINT , SIGSEGV , SIGTERM , or SIGBREAK . A ValueError will be raised in any other case. Note that not all systems define the same set of signal names; an AttributeError will be raised if a signal name is not defined as SIG* module level constant.
Examine the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). Return the set of the pending signals.
Availability : Unix. See the man page sigpending(2) for further information.
New in version 3.3.
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal (removes it from the pending list of signals), and returns the signal number.
Availability : Unix. See the man page sigwait(3) for further information.
New in version 3.3.
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal and removes it from the pending list of signals. If one of the signals in sigset is already pending for the calling thread, the function will return immediately with information about that signal. The signal handler is not called for the delivered signal. The function raises an InterruptedError if it is interrupted by a signal that is not in sigset.
The return value is an object representing the data contained in the siginfo_t structure, namely: si_signo , si_code , si_errno , si_pid , si_uid , si_status , si_band .
Availability : Unix. See the man page sigwaitinfo(2) for further information.
New in version 3.3.
Changed in version 3.5: The function is now retried if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale).
Like sigwaitinfo() , but takes an additional timeout argument specifying a timeout. If timeout is specified as 0 , a poll is performed. Returns None if a timeout occurs.
Availability : Unix. See the man page sigtimedwait(2) for further information.
New in version 3.3.
Changed in version 3.5: The function is now retried with the recomputed timeout if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale).
ExampleВ¶
Here is a minimal example program. It uses the alarm() function to limit the time spent waiting to open a file; this is useful if the file is for a serial device that may not be turned on, which would normally cause the os.open() to hang indefinitely. The solution is to set a 5-second alarm before opening the file; if the operation takes too long, the alarm signal will be sent, and the handler raises an exception.
Note on SIGPIPEВ¶
Piping output of your program to tools like head(1) will cause a SIGPIPE signal to be sent to your process when the receiver of its standard output closes early. This results in an exception like BrokenPipeError: [Errno 32] Broken pipe . To handle this case, wrap your entry point to catch this exception as follows:
Do not set SIGPIPE ’s disposition to SIG_DFL in order to avoid BrokenPipeError . Doing that would cause your program to exit unexpectedly also whenever any socket connection is interrupted while your program is still writing to it.