from threading import Thread
from time import sleep
import sys
def timer():
for i in range(45):
sleep(1) #waits 45 seconds
sys.exit() #stops program after timer runs out, you could also have it print something or keep the user from attempting to answer any longer
def question():
answer = input("foo?")
t1 = Thread(target=timer)
t2 = Thread(target=question)
t1.start() #Calls first function
t2.start() #Calls second function to run at same time
使用
threading
模块一次运行多个线程您可以使用Python
threading
模块使两件事同时发生,从而允许用户在计时器计时的同时回答。一些示例代码利用了这一点:
这并不完美,但这段代码应该启动两个不同的线程,一个问问题,一个在终止程序前45秒超时。有关
threading
的更多信息,请参见the docs。希望这对你的项目有帮助!尝试使用time.time()。这返回自1970年1月1日以来在UNIXTime中的秒数。然后可以创建while循环,以便:
希望这有帮助!
相关问题 更多 >
编程相关推荐