【发布时间】:2017-11-06 20:06:37
【问题描述】:
我已经搜索了一段时间,但我没有找到有效的方法 我想做的是这样的:
prompt=str(input('press "l" within two seconds:'):
if prompt=='l':
print('ta da')
else:
print('loser')
如何添加时间限制?
【问题讨论】:
标签: python-3.x time
我已经搜索了一段时间,但我没有找到有效的方法 我想做的是这样的:
prompt=str(input('press "l" within two seconds:'):
if prompt=='l':
print('ta da')
else:
print('loser')
如何添加时间限制?
【问题讨论】:
标签: python-3.x time
如果您不关心线程安全,这是一个很好的方法:
import datetime
import threading
win = False
time_out = False
def MyThread1(t_name, prompt, time_var):
global win
global time_out
prompt=str(input('press "l" within two seconds:'))
win = False
if(not time_out and prompt == 'l'):
win = True
print('ta da')
else:
print('loser')
def MyThread2(t_name, prompt, time_var):
global win
global time_out
while (time_var > datetime.datetime.now()):
pass
time_out = True
time_var = datetime.datetime.now() + datetime.timedelta(seconds=2)
prompt = 'l'
t1 = threading.Thread(target=MyThread1, args=("Thread-1", prompt, time_var))
t2 = threading.Thread(target=MyThread2, args=("Thread-2", prompt, time_var))
t1.start()
t2.start()
【讨论】: