Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

To do timeout on a function call you can use multiprocessing.Process below is the code for the same:-

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()

Browse Categories

...