Created
March 28, 2019 11:50
-
-
Save gustavorv86/80858bfdec6146400122cfaca6bb1cda to your computer and use it in GitHub Desktop.
Python: execute a function with timeout using signals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import signal | |
import time | |
class SigalrmException(Exception): | |
pass | |
def sigalrm_handler(signum, frame): | |
raise SigalrmException() | |
def fn_loop_count(message, start_count, end_count): | |
for i in range(start_count, end_count): | |
print(message + ": " + str(i)) | |
start_count +=1 | |
time.sleep(1) | |
return "OK" | |
def exec_with_timeout(function_name, args, timeout): | |
signal.signal(signal.SIGALRM, sigalrm_handler) | |
signal.alarm(timeout) | |
try: | |
retval = function_name(*args) # Convert tuple in args | |
return retval | |
except SigalrmException: | |
retval = None | |
signal.alarm(0) | |
return retval | |
if __name__ == "__main__": | |
args = ("Hola Mundo", 10, 12, ) | |
status = exec_with_timeout(fn_loop_count, args, 5) | |
print("Status: {}".format(status)) | |
args = ("Hola Mundo", 50, 100, ) | |
status = exec_with_timeout(fn_loop_count, args, 5) | |
print("Status: {}".format(status)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment