Timeout on a function call

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

    We can use signals for the same. I think the below example will be useful for you. It is very simple compared to threads.

    import signal
    
    def timeout(signum, frame):
        raise myException
    
    #this is an infinite loop, never ending under normal circumstances
    def main():
        print 'Starting Main ',
        while 1:
            print 'in main ',
    
    #SIGALRM is only usable on a unix platform
    signal.signal(signal.SIGALRM, timeout)
    
    #change 5 to however many seconds you need
    signal.alarm(5)
    
    try:
        main()
    except myException:
        print "whoops"
    

提交回复
热议问题