Python 如何为函数设置计时器
我已收到此代码,希望添加一个计时器,如果在一定时间内未完成回答,则会显示gameover。您希望线程模块中包含计时器类Python 如何为函数设置计时器,python,python-3.x,Python,Python 3.x,我已收到此代码,希望添加一个计时器,如果在一定时间内未完成回答,则会显示gameover。您希望线程模块中包含计时器类 def choosePath(): path = "" while path != "e" and path !="n": print('\nWhich way do you go (n, s, e, w):\n') t = Timer(1 * 1, timeout) t.start() answe
def choosePath():
path = ""
while path != "e" and path !="n":
print('\nWhich way do you go (n, s, e, w):\n')
t = Timer(1 * 1, timeout)
t.start()
answer = input(path)
path = path.lower()
if path =="e":
station()
elif path =="n":
estate()
elif path =="s":
building()
else:
print("\nYou return the way you came are but are soon caught by Mansons and assimilated.\n")
return path
导入线程
t=线程。计时器(,[])
t、 开始()
如果用户在time call
t.cancel()中选择了一个选项,则需要在while循环之外启动计时器。也有几种方法可以实现计时器,但这应该是可行的(我简化了它,您需要根据您的业务逻辑调整它)
尝试创建另一个线程来跟踪时间,然后更新全局布尔值:
import time
start_time = datetime.now()
max_time_allowed = 45
while path != "e" and path !="n":
#Business logic here
current_time= datetime.now()
if current_time-start_time > max_time_allowed:
return
现在,您可以使主代码在while
循环中有一个附加语句:
from threading import Thread
from time import sleep
timeIsUp = False
threadKill = False
def answerTime(self):
sleep(self)
if threadKill = True:
self._is_running = False
else:
timeIsUp = True
self._is_running = False
thread = Thread(target = answerTime, args = (10)
回溯(最近一次调用):文件“\\oat.int\home$\acs\student\2015\15SrokaTy\Documents\Python Coding\IOT adventure-无人能生存..py”,backstory()文件“\\oat.int\home$\acs\student\2015\15SrokaTy\Documents\Python Coding\IOT adventure-无人能生存..py”第23行,在backstory时间。睡眠(0)AttributeError:'builtin_function_或_method'对象没有属性'sleep'第1行从时间导入时间应该是导入时间,请更新您的posthmm,刚刚意识到我没有完全理解这个问题,有办法删除这个吗?
from threading import Thread
from time import sleep
timeIsUp = False
threadKill = False
def answerTime(self):
sleep(self)
if threadKill = True:
self._is_running = False
else:
timeIsUp = True
self._is_running = False
thread = Thread(target = answerTime, args = (10)
while path != "e" and path !="n" and timeIsUp==False:
...
if path =="e":
station()
threadKill=True
elif path =="n":
estate()
threadKill=True
elif path =="s":
building()
threadKill=True
else:
print("Time is up")