python限制函数调用执行时间

from multiprocessing import Process from time import sleepdef f(time): sleep(time)def run_with_limited_time(func, args, kwargs, time): """Runs a function with time limit:param func: The function to run调用方法 :param args: The functions args, given as tuple方法传参 :param kwargs: The functions keywords, given as dict :param time: The time limit in seconds设置的限制时间 :return: True if the function ended successfully. False if it was terminated. """ p = Process(target=func, args=args, kwargs=kwargs) p.start() p.join(time) if p.is_alive(): p.terminate() return Falsereturn Trueif __name__ == '__main__': print(run_with_limited_time(f, (1.5, ), {}, 2.5)) # True print(run_with_limited_time(f, (3.5, ), {}, 2.5)) # False

    推荐阅读