Python code execution timeout judgment

  1. Through the signal signal processing function

import signal
#custom exception class (inherited from BaseException so, this way Exception i can't capture it 
class TimeoutException(BaseException):
pass
#timeout signal function 
def set_timeout(seconds):
#set signal reception function( signal.signal(sig,action),sig for signals, action for signal processing functions) 
signal.signal(signal.SIGALRM, timeout_handler)
#send SIGALRM timeout signal 
signal.alarm(seconds)
#signal processing function( signum the signal number, frame the stack frame at the moment of signal interruption 
def timeout_handler(signum, frame):
raise TimeoutException("execution timeout exception")
 main function 
def main():
try:
  #firstly, the signal processing function for registering timeout warnings is given a timeout time of 10 seconds 
  set_timeout(10)
  #then, the code segments that need to be monitored can be executed, such as sql queries, complex calculations, etc 
  ...
  #finally, if the above code snippet is completed within the timeout period, the timer should be turned off ; if the above code is not completed within the timeout period, the signal processing function will be triggered timeout_handler (), which means throwing an exception, we can capture and further process it 
  signal.alarm(0)
except TimeoutException as e:
  print(e)
  1. Through eventlet (a library that handles network and concurrency)

import eventlet
#main function 
def main():
#before setting the timeout function, this line of code must be executed to introduce path
eventlet.monkey_patch()

try:
  #set timeout function (the first parameter is the timeout time of 10 seconds ; if the second parameter is True if timeout occurs, an exception will be triggered. if it is False will not trigger an exception, but it will be skipped with eventlet the remaining code within the code snippet, with eventlet other code outside the code snippet will still execute normally 
  with eventlet.Timeout(10, True):
      #then, the code segments that need to be monitored can be executed, such as sql queries, complex calculations, etc 
      ...
  
  #other code, code after monitoring completion 
  ...
except eventlet.timeout.Timeout as e:
# except:   #or this method can also capture 
  print(e)

Related articles