Timeout on a function call

后端 未结 18 1532
挽巷
挽巷 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:11

    Great, easy to use and reliable PyPi project timeout-decorator (https://pypi.org/project/timeout-decorator/)

    installation:

    pip install timeout-decorator
    

    Usage:

    import time
    import timeout_decorator
    
    @timeout_decorator.timeout(5)
    def mytest():
        print "Start"
        for i in range(1,10):
            time.sleep(1)
            print "%d seconds have passed" % i
    
    if __name__ == '__main__':
        mytest()
    

提交回复
热议问题