I am calling a function in Python which I know that I can be forced to restart the script
How do I call the function or how to wrap it, so if it takes more than 5 seconds then cancel the script and do something else?
If you are running on UNIX, then you can use the package:
< In the pre: [1]: Import sign # Register a handler for time [2]: Deaf Handler (Sigmum, Frame): ...: Print "is always over!" ...: Exception ("end of time") ...: # This function * * can run for indefinite time ... in [3]: def loop_forever (): ...: import time .. : While: 1: ...: print "seconds" ...: time sleep (1) ...: ...: # register the signal function handler [4]: signal.signal (signal.SIGALRM , Handler) Out [4]: 0 # Set a timeout for your function [5]: signal.alarm (10) out [5]: in 0 [6]: try: ...: loop_forever ( ) ...: Exception except, exc: ...: print exc ....: sec sec sec second should always end Interpretation is! End of time # Cancel the timer when the function returns back to # time (OK, mine will not be mine but will be :) in: [7]: signal.alarm (0) out [7]: 0
< / Pre> Alarms after 10 seconds of call. The alarm (10)
is called the handler. It raises an exception that you can stop with regular Python code.
This module does not play well with threads (but then, who does?)
Note that because after the expiration of we Increase an exception, can be caught inside the function and ignored, for example, such a task:
def loop_forever (): while 1: try 'sec': time.sleep (10): Continue
Comments
Post a Comment