The Python documentation for signal reads:
• Although Python signal handlers are called asynchronously as long as the Python user, they can only occur between the "atomic" instructions of the Python interpreter. This means that signals arriving during lengthy calculations performed exclusively in C (for example, regular expression matches on large text bodies) can be delayed for an arbitrary amount of time.
while time says:
The actual pause time may be less than the requested one, since any caught signal will stop sleep () after this signal is executed.
On Windows, apparently, time.sleep() not executed according to the documentation, since the signal handler received during sleep does not work until the full duration of sleep has ended. The following example:
import signal, time def handler(signum, frame): print('Signal handler called with signal', signum) signal.signal(signal.SIGINT, handler) print("signal set, sleeping") time.sleep(10) print("sleep done")
prints:
signal set, sleeping Signal handler called with signal 2 sleep done
when the first line occurs immediately, and the second after 10 seconds, regardless of when the interrupt occurs.
According to Thomas K, the best strategy would be to use threads and synchronization.
Dave
source share