How to limit execution time of a function call in Python

后端 未结 10 1920
遥遥无期
遥遥无期 2020-11-22 10:25

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which

10条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 10:57

    I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.

    http://docs.python.org/library/signal.html

    So your code is going to look something like this.

    import signal
    
    def signal_handler(signum, frame):
        raise Exception("Timed out!")
    
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(10)   # Ten seconds
    try:
        long_function_call()
    except Exception, msg:
        print "Timed out!"
    

提交回复
热议问题