custom timeout function python code example

Example: python timeout

You may use the signal package if you are running on UNIX:

import signal

# Register an handler for the timeout
def handler(signum, frame):
  print("Forever is over!")
       raise Exception("end of time")
   

# This function *may* run for an indetermined time...
def loop_forever():
     import time
     while 1:
         print("sec")
         time.sleep(1)
         
         

# Register the signal function handler
signal.signal(signal.SIGALRM, handler)


# Define a timeout for your function
signal.alarm(10)
0

try:
    loop_forever()
except Exception, exc:
    print(exc)