python限制函数调用执行时间

from multiprocessing import Process
from time import sleep

def 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 True


if __name__ == '__main__':
    print(run_with_limited_time(f, (1.5, ), {}, 2.5)) # True
    print(run_with_limited_time(f, (3.5, ), {}, 2.5)) # False

你可能感兴趣的