Function Timeout Handling in Python
When calling a function that might execute indefinitely or encounter issues that require script termination, a timeout mechanism is useful. In Python, we can utilize the following methods to handle function timeouts gracefully.
Using the signal Module:
If running on a UNIX system, the signal package provides a way to handle timeouts. By registering a timeout handler, we can cancel the function execution if it exceeds the predetermined time limit. Here's an example using signal:
import signal # Register a handler for the timeout def handler(signum, frame): print("Forever is over!") raise Exception("end of time") # Define a potentially long-running function def loop_forever(): import time while 1: print("sec") time.sleep(1) # Set up the signal handler signal.signal(signal.SIGALRM, handler) # Define the timeout duration (in seconds) timeout = 10 signal.alarm(timeout) # Attempt to execute the function try: loop_forever() except Exception as exc: print(exc) # Cancel the timeout after the function completes signal.alarm(0)
When the function loop_forever() exceeds the 10-second timeout, the handler function is called, raising an exception that can be handled in the main code.
Note:
It's important to use the signal module with caution. It's not fully thread-safe, so it's best to avoid using it in multi-threaded applications.
The above is the detailed content of How Can I Gracefully Handle Function Timeouts in Python?. For more information, please follow other related articles on the PHP Chinese website!