关于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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理