from multiprocessing import Processfrom 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 False return 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