限时输入?[重复]
- 2024-12-18 08:39:00
- admin 原创
- 171
问题描述:
我希望能够使用输入向用户提问。例如:
print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...
")
然后如果时间过去了,打印类似
print('Sorry, times up.')
任何能为我指明正确方向的帮助都将不胜感激。
解决方案 1:
如果在用户未提供答案时可以阻止主线程:
from threading import Timer
timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...
" % timeout
answer = input(prompt)
t.cancel()
否则,您可以在 Windows 上使用@Alex Martelli 的答案(针对 Python 3 进行了修改)(未经测试):
import msvcrt
import time
class TimeoutExpired(Exception):
pass
def input_with_timeout(prompt, timeout, timer=time.monotonic):
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == '
':
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
用法:
try:
answer = input_with_timeout(prompt, 10)
except TimeoutExpired:
print('Sorry, times up')
else:
print('Got %r' % answer)
在 Unix 上你可以尝试:
import select
import sys
def input_with_timeout(prompt, timeout):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [],[], timeout)
if ready:
return sys.stdin.readline().rstrip('
') # expect stdin to be line-buffered
raise TimeoutExpired
或者:
import signal
def alarm_handler(signum, frame):
raise TimeoutExpired
def input_with_timeout(prompt, timeout):
# set signal handler
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout) # produce SIGALRM in `timeout` seconds
try:
return input(prompt)
finally:
signal.alarm(0) # cancel alarm
解决方案 2:
有趣的问题,这似乎有效:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD