我正在为我朋友的班级做一个简单的数学测试。学生将只有 45 秒的时间来解决每个答案。有没有办法制作一个计时器,它会在其余代码运行的同时计数,并且当它达到 45 次停止时?
测试看起来像这样:
test = raw_input("How much is 62x5-23?")
if test == '287':
print "Well done!"
我正在为我朋友的班级做一个简单的数学测试。学生将只有 45 秒的时间来解决每个答案。有没有办法制作一个计时器,它会在其余代码运行的同时计数,并且当它达到 45 次停止时?
测试看起来像这样:
test = raw_input("How much is 62x5-23?")
if test == '287':
print "Well done!"
这是我曾经使用过的一些代码(从网络上的某些页面上取下来,现在在域名抢注者手中,因此遗憾的是,没有信用到期的信用):
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 类型的操作系统。