Timeout on a function call

后端 未结 18 1567
挽巷
挽巷 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 04:59

    There are a lot of suggestions, but none using concurrent.futures, which I think is the most legible way to handle this.

    from concurrent.futures import ProcessPoolExecutor
    
    # Warning: this does not terminate function if timeout
    def timeout_five(fnc, *args, **kwargs):
        with ProcessPoolExecutor() as p:
            f = p.submit(fnc, *args, **kwargs)
            return f.result(timeout=5)
    

    Super simple to read and maintain.

    We make a pool, submit a single process and then wait up to 5 seconds before raising a TimeoutError that you could catch and handle however you needed.

    Native to python 3.2+ and backported to 2.7 (pip install futures).

    Switching between threads and processes is as simple as replacing ProcessPoolExecutor with ThreadPoolExecutor.

    If you want to terminate the Process on timeout I would suggest looking into Pebble.

提交回复
热议问题