Wednesday, 15 April 2015

python - Stop code after time period -



python - Stop code after time period -

this question has reply here:

timeout on python function call 10 answers

i phone call foo(n) stop if runs more 10 seconds. what's way this?

i can see in theory modify foo periodically check how long has been running prefer not that.

here go:

import multiprocessing import time # foo function def foo(n): in range(10000 * n): print "tick" time.sleep(1) if __name__ == '__main__': # start foo process p = multiprocessing.process(target=foo, name="foo", args=(10,)) p.start() # wait 10 seconds foo time.sleep(10) # terminate foo p.terminate() # cleanup p.join()

this wait 10 seconds foo , kill it.

update

terminate process if running.

# if thread active if p.is_alive(): print "foo running... let's kill it..." # terminate foo p.terminate()

update 2 : recommended

use join timeout. if foo finishes before timeout, main can continue.

# wait maximum of 10 seconds foo # usage: join([timeout in seconds]) p.join(10) # if thread active if p.is_alive(): print "foo running... let's kill it..." # terminate foo p.terminate() p.join()

python

No comments:

Post a Comment