How to add a timeout to a function in Python

前端 未结 5 925
说谎
说谎 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:35

    The Pebble library was designed to offer cross-platform implementation capable of dealing with problematic logic which could crash, segfault or run indefinitely.

    from pebble import concurrent
    
    @concurrent.process(timeout=10)
    def function(foo, bar=0):
        return foo + bar
    
    future = function(1, bar=2)
    
    try:
        result = future.result()  # blocks until results are ready
    except Exception as error:
        print("Function raised %s" % error)
        print(error.traceback)  # traceback of the function
    except TimeoutError as error:
        print("Function took longer than %d seconds" % error.args[1])
    

    The decorator works as well with static and class methods. I would not recommend to decorate methods nevertheless, as it is a quite error prone practice.

提交回复
热议问题