在Python中设置定时器
大家好,我正在用Python写一个程序。这个程序是一个计算器,它会随机给你两个从2到10之间的数字,然后问你,比如2乘以4等于多少。
如果你的答案是对的,它就会给你加一分。现在,我想让这个程序让用户计算20秒,等到20秒结束后,它会告诉你你得了多少分。
到目前为止我的代码是 ->
__author__ = 'Majky'
import random
import time
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
t = 0
odg = int(input("Answer ?"))
sec = 0
while sec < 20:
if odg == a * b:
print("Correct")
t = +1
print("Incorrect")
print("Your points are", t)
3 个回答
你可以使用 time.sleep(20)
这个函数来等待20秒。
这个函数会暂停程序的运行,暂停的时间是你指定的秒数。你可以用小数来表示更精确的暂停时间。
实际的暂停时间可能会比你要求的短,因为如果有信号被捕获,程序会在处理完这个信号后才继续执行 sleep()
。另外,暂停的时间也可能会比你要求的长,这可能是因为系统中其他活动的调度影响。
你可以像这样做,使用 time.time()
。
import time
...
start = time.time()
answer = raw_input('enter solution')
finish = time.time()
if finish - start > 20:
#failure condition
else:
#success condition
你需要使用threading模块,开启一个并行线程来计算时间(可以用time.sleep()来实现),等计算完成后再返回结果。一旦这个线程返回,主线程就会停止执行并返回结果。
如果在主程序中使用sleep(),那就会让程序暂停一段时间,这不是你想要的。你希望用户在计时的同时还能和程序互动。使用threading模块的线程可以实现这个需求。
下面是一个使用线程的简单示例(如果你有特别的需求,可以根据需要调整):
import random
import time
def main():
thread_stop = threading.Event()
thread = threading.Thread(target=user_thread, args=(2, thread_stop))
time.sleep(20)
thread_stop.set()
def user_thread(arg1, stop_event):
t = 0
while(not stop_event.is_set()):
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
odg = int(input("Answer ?"))
if odg == a * b:
print("Correct")
t += 1
else:
print("Incorrect")
print("Your points are", t)
main()
还有一个例子是使用信号来控制,如果20秒到了,就会在用户回答的过程中停止,并计算结果。这个例子使用了信号模块,这个模块本身也很有趣,可以用来控制程序的执行流程,等你有时间可以去看看它的文档。
我还发现你代码中有另一个错误我之前没注意到,现在在两个例子中都已经修正了。当你想增加“t”的值时,应该用“t+=1”,因为“t=+1”是错误的,后者每次只是把“正数1”赋值给t,并没有增加它的值。祝好运!
import signal
t = 0
#Here we register a handler for timeout
def handler(signum, frame):
#print "Time is up!"
raise Exception("Time is up.")
#function to execute your logic where questions are asked
def looped_questions():
import random
global t
while 1:
#Here is the logic for the questions
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
odg = int(input("Answer ?"))
if odg == a * b:
t += 1
print("Correct")
else:
print("Incorrect")
#Register the signal handler
signal.signal(signal.SIGALRM, handler)
#Set the timeout
signal.alarm(20)
try:
looped_questions()
except Exception, exc:
print exc
#Here goes the results logic
print("Your points are", t)
另外,别忘了加一些检查,以确保无效的用户输入不会导致你的代码出错。这部分我就留给你自己去做;)