python运行超时设置


import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message="Timer expired"):
    def _timeout(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wrapper

    return _timeout

There are comments.