Multi-threading with a simple timer?

Robin Becker robin at reportlab.com
Tue Jul 3 03:36:43 EDT 2018


On 03/07/2018 07:12, Gregory Ewing wrote:
> import signal, sys
> 
> def timeout(*args):
>      print("Too late!")
>      sys.exit(0)
> 
> signal.signal(signal.SIGALRM, timeout)
> signal.setitimer(signal.ITIMER_REAL, 15)
> data = input("Enter something: ")
> print("You entered: ", data)

This doesn't work in windows (SIGALRM not available see
https://stackoverflow.com/questions/6947065/right-way-to-run-some-code-with-timeout-in-python)

For completeness I think it needs the handler restoring; this seemed to work for me in linux; I did try using SIG_DFL, but 
apparently that just prints 'Alarm clock' and exits at least

import signal, sys, time

def timeout(*args):
         print("Too late!")
         sys.exit(0)

signal.signal(signal.SIGALRM, timeout)
signal.setitimer(signal.ITIMER_REAL, 15)
data = input("Enter something: ")
signal.signal(signal.SIGALRM,signal.SIG_IGN)
print("You entered: ", data)
for i in reversed(xrange(15)):
         print i
         time.sleep(1)

print 'finished!'


if I leave out the signal.signal(signal.SIGALRM,signal.SIG_IGN) then the timeout function gets called anyway.
-- 
Robin Becker



More information about the Python-list mailing list