Home >Backend Development >Python Tutorial >How Can I Prevent Indefinitely Halting Python Functions with a Timeout?
Timeout on Function Calls
When invoking a function in Python that may halt the script's execution indefinitely, it becomes necessary to establish a mechanism to prevent it. The solution lies in setting a timeout threshold after which the script will intervene and terminate the function.
Using the Signal Package
For UNIX-based systems, the signal package offers a robust solution. To utilize it:
Here is an illustrative example:
import signal # Handler function def handler(signum, frame): print("Timeout reached!") raise Exception("Timeout exception") # Function that may stall indefinitely def loop_forever(): while True: print("Looping") # Pause execution for 1 second time.sleep(1) # Set timeout to 5 seconds signal.alarm(5) signal.signal(signal.SIGALRM, handler) try: loop_forever() except Exception as exc: print("Exception:", exc)
If the function loop_forever() fails to complete within 5 seconds, the handler function will be invoked, raising the timeout exception and terminating the process.
The above is the detailed content of How Can I Prevent Indefinitely Halting Python Functions with a Timeout?. For more information, please follow other related articles on the PHP Chinese website!