Back
I'm calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
To do timeout on a function call you can use multiprocessing.Process below is the code for the same:-
import multiprocessingimport timedef bar():for i in range(100):print "Tick"time.sleep(1)if __name__ == '__main__':p = multiprocessing.Process(target=bar)p.start() p.join(10) if p.is_alive():print "running... let's kill it..." p.terminate()p.join()
import multiprocessing
import time
def bar():
for i in range(100):
print "Tick"
time.sleep(1)
if __name__ == '__main__':
p = multiprocessing.Process(target=bar)
p.start()
p.join(10)
if p.is_alive():
print "running... let's kill it..."
p.terminate()
p.join()
31k questions
32.8k answers
501 comments
693 users