乐趣区

关于python: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
退出移动版