How to add a timeout to a function in Python

前端 未结 5 909
说谎
说谎 2020-12-02 16:06

Many attempts have been made in the past to add timeout functionality in Python such that when a specified time limit expired, waiting code could move on. Unfortunately, pre

5条回答
  •  离开以前
    2020-12-02 16:29

    This is how to get the decorator syntax Jerub mentioned

    def timeout(limit=None):
        if limit is None:
            limit = DEFAULT_TIMEOUT
        if limit <= 0:
            raise TimeoutError() # why not ValueError here?
        def wrap(function):
            return _Timeout(function,limit)
        return wrap
    
    @timeout(15)
    def mymethod(): pass
    

提交回复
热议问题