right way to run some code with timeout in Python

后端 未结 9 1733
余生分开走
余生分开走 2020-12-13 18:18

I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches:

  • Use threa
9条回答
  •  庸人自扰
    2020-12-13 19:02

    What you might be looking for is the multiprocessing module. If subprocess is too heavy, then this may not suit your needs either.

    import time
    import multiprocessing
    
    def do_this_other_thing_that_may_take_too_long(duration):
        time.sleep(duration)
        return 'done after sleeping {0} seconds.'.format(duration)
    
    pool = multiprocessing.Pool(1)
    print 'starting....'
    res = pool.apply_async(do_this_other_thing_that_may_take_too_long, [8])
    for timeout in range(1, 10):
        try:
            print '{0}: {1}'.format(duration, res.get(timeout))
        except multiprocessing.TimeoutError:
            print '{0}: timed out'.format(duration) 
    
    print 'end'
    

提交回复
热议问题