Timeout a Function with a Deadline
In shell scripting, it's common to encounter cases where certain tasks, such as screengrabbing websites, can become unexpectedly time-consuming or even fail to complete. To address this, we can implement a timeout mechanism to terminate a function if it exceeds a predetermined time limit.
One approach to implementing a timeout is to use Python's signal module. This module allows us to set a timer and raise an exception when the time expires. However, it's important to note that this solution is only applicable in UNIX environments.
To implement the timeout functionality, we can create a decorator called @timeout using the code provided in the response. This decorator can be applied to any long-running function to enforce a time limit. Here's a modified version of the code for clarity:
import errno import os import signal import functools class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) @functools.wraps(func) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator
Here's how to use the @timeout decorator in your code:
from timeout import timeout @timeout def my_long_running_function(): ... def my_main_function(): try: my_long_running_function() except TimeoutError as e: print(e)
By applying the @timeout decorator to my_long_running_function, it now has a 10-second time limit. If the function exceeds this deadline, it will raise a TimeoutError exception, which can be handled in your main function. This mechanism ensures that your script does not get stuck indefinitely due to slow or unresponsive tasks.
The above is the detailed content of How Can I Set a Timeout for a Function in Python to Prevent Deadlocks?. For more information, please follow other related articles on the PHP Chinese website!