Timeout on a function call

后端 未结 18 1472
挽巷
挽巷 2020-11-21 04:53

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

18条回答
  •  伪装坚强ぢ
    2020-11-21 05:03

    You can use multiprocessing.Process to do exactly that.

    Code

    import multiprocessing
    import time
    
    # bar
    def bar():
        for i in range(100):
            print "Tick"
            time.sleep(1)
    
    if __name__ == '__main__':
        # Start bar as a process
        p = multiprocessing.Process(target=bar)
        p.start()
    
        # Wait for 10 seconds or until process finishes
        p.join(10)
    
        # If thread is still active
        if p.is_alive():
            print "running... let's kill it..."
    
            # Terminate - may not work if process is stuck for good
            p.terminate()
            # OR Kill - will work for sure, no chance for process to finish nicely however
            # p.kill()
    
            p.join()
    

提交回复
热议问题