python 函数超时装饰器

#-*-coding:utf8-*-

import time

import signal


def handler(signum, frame):

    raise AssertionError


def timeout(arg):

    def _deco(func):

        def __deco(*args,**kwargs):

            try:

                signal.signal(signal.SIGALRM, handler)

                signal.alarm(arg)

                func(*args,**kwargs)

                signal.alarm(0)

            except AssertionError:

                print "timeout,%s"%arg


        return __deco

    return _deco

@timeout(5)

def test(i=5):

    time.sleep(i)

    print "%d sleep time"%(i)

    return i


你可能感兴趣的:(python 函数超时装饰器)