如何使计时器与Python中的其余代码同时运行?

时间:2013-10-13 16:58:24

标签: python-2.7

我正在为我朋友的班级做一个简单的数学考试。学生只有45秒的时间来解决每个答案。有没有办法让计时器在其余代码运行的同时计数到达45个停止位置?

测试如下:

test = raw_input("How much is 62x5-23?")
if test == '287':
    print "Well done!"

1 个答案:

答案 0 :(得分:0)

以下是我曾经使用过的一些代码(取消了网页上的一些页面,现在掌握在域名抢注者的手中,所以没有信用可靠的信用,遗憾的是):

import signal

class TimeoutException(Exception):
    pass

def timeout(timeout_time, default = None):
    def timeout_function(f):
        def f2(*args, **kwargs):
            def timeout_handler(signum, frame):
                raise TimeoutException()

            old_handler = signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(timeout_time) # triger alarm in timeout_time seconds
            try:
                retval = f(*args, **kwargs)
            except TimeoutException, e:
                if default == None:
                    raise e
                return default
            finally:
                signal.signal(signal.SIGALRM, old_handler)
            signal.alarm(0)
            return retval
        return f2
    return timeout_function

# use like this:
@timeout(45)
def run():
    test = raw_input("How much is 62x5-23? ")
    if test == '287':
        print "Well done!"

# alternatively, pass a value that will be returned when the timeout is reached:
@timeout(45, False)
def run2():
    test = raw_input("How much is 62x5-23? ")
    if test == '287':
        print "Well done!"

if __name__ == '__main__':
    try:
        run()
    except TimeoutException:
        print "\nSorry, you took too long."

    # alternative call:
    if run2() == False:
        print "\nSorry, you took too long."

编辑:可能仅适用于Unix类型的操作系统。