Timeout on a function call

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

    Another solution with asyncio :

    import asyncio
    import functools
    import multiprocessing
    from concurrent.futures.thread import ThreadPoolExecutor
    
    
    class SingletonTimeOut:
        pool = None
    
        @classmethod
        def run(cls, to_run: functools.partial, timeout: float):
            pool = cls.get_pool()
            loop = cls.get_loop()
            try:
                task = loop.run_in_executor(pool, to_run)
                return loop.run_until_complete(asyncio.wait_for(task, timeout=timeout))
            except asyncio.TimeoutError as e:
                error_type = type(e).__name__ #TODO
                raise e
    
        @classmethod
        def get_pool(cls):
            if cls.pool is None:
                cls.pool = ThreadPoolExecutor(multiprocessing.cpu_count())
            return cls.pool
    
        @classmethod
        def get_loop(cls):
            try:
                return asyncio.get_event_loop()
            except RuntimeError:
                asyncio.set_event_loop(asyncio.new_event_loop())
                # print("NEW LOOP" + str(threading.current_thread().ident))
                return asyncio.get_event_loop()
    
    # ---------------
    
    TIME_OUT = float('0.2')  # seconds
    
    def toto(input_items,nb_predictions):
        return 1
    
    to_run = functools.partial(toto,
                               input_items=1,
                               nb_predictions="a")
    
    results = SingletonTimeOut.run(to_run, TIME_OUT)
    
    

提交回复
热议问题