Handling Function Timeouts in Python
When calling a function that may potentially stall, it becomes crucial to have a mechanism in place to gracefully handle such situations and prevent the script from freezing indefinitely. One effective solution to this problem is to set a timeout for the function call.
The Python signal module provides the necessary functionality to register a signal handler that will be invoked if the function exceeds the specified timeout. Here's how it can be implemented:
import signal def handler(signum, frame): print("Timeout reached!") raise Exception("Function call timed out") def function_to_timeout(): print("Running function...") # Simulate a long-running task for i in range(10): time.sleep(1) # Register the signal handler signal.signal(signal.SIGALRM, handler) # Set a timeout of 5 seconds signal.alarm(5) try: # Call the function function_to_timeout() except Exception as exc: print(exc)
When the function_to_timeout() is called, it will print a message indicating that it is running. The signal.alarm(5) sets a 5-second timeout, after which the handler function will be triggered. Within the handler, an exception is raised to terminate the function call.
This approach allows you to set a specific timeout for the function and gracefully exit the script in case the function takes longer than the specified time.
The above is the detailed content of How to Handle Function Timeouts in Python?. For more information, please follow other related articles on the PHP Chinese website!