Friday, December 18, 2020

implementing function timeout in python

Advertisements

At many times we wished if we could break and/or continue a python function when the function takes a lot of time to complete. We can achieve this using signal and time modules. 

[root@dockerhost ~]# cat test.py
#!/usr/bin/python
import re
import signal
import time
import sys

def timeoutHandler(signum,frame):
  raise Exception("Timeout")

"""Set alarm timer to 10s"""
signal.signal(signal.SIGALRM, timeoutHandler)
signal.alarm(10)

"""The try block will timeout if it couldn't finish it under 10s"""
try:
  time.sleep(int(sys.argv[1]))
  if re.search('abc','abcd',re.I|re.M):
    print("yaay!")
except Exception, e:
    print(e)
finally:
  """To cancel the scheduled alarm"""
  signal.alarm(0)

[root@dockerhost ~]# ./test.py 5
yaay!
[root@dockerhost ~]# ./test.py 15
Timeout
[root@dockerhost ~]#