我正在使用Python 3,我想编写一个程序,该程序在一定时间内要求多个用户输入。这是我的尝试:
from threading import Timer
##
def timeup():
global your_time
your_time = False
return your_time
##
timeout = 5
your_Time = True
t = Timer(timeout, timeup)
t.start()
##
while your_time == True:
input()
t.cancel()
print('Stop typing!')
问题是,即使时间到了,代码仍然等待输入。我希望循环在时间用完时停止。我该怎么做呢?谢谢!
答案 0 :(得分:2)
您可以使用poll()方法(在Linux上经过测试):
import select,sys
def timed_input(sec):
po= select.poll() # creating a poll object
# register the standard input for polling with the file number
po.register(sys.stdin.fileno(), select.POLLIN)
while True:
# start the poll
events= po.poll(sec*1000) # timeout: milliseconds
if not events:
print("\n Sorry, it's too late...")
return ""
for fno,ev in events: # check the events and the corresponding fno
if fno == sys.stdin.fileno(): # in our case this is the only one
return(input())
s=timed_input(10)
print("From keyboard:",s)
stdin缓冲按下的键,然后input()函数立即读取该缓冲区。
答案 1 :(得分:2)
此解决方案是与平台无关的,并且立即会中断键入以通知现有的超时。不必等到用户按下ENTER键即可确定发生了超时。除了及时通知用户之外,这还可以确保在进一步处理超时后不再输入任何内容。
功能
此答案使用线程管理器实例,该实例在一个
单独的提示线程和MainThread。管理器线程检查超时,并将输入从提示线程转发到父线程。这种设计使得在MainThread需要非阻塞(更改_poll
来替换阻塞queue.get()
的情况下)的修改很容易。
在超时时,管理器线程要求ENTER继续并使用
threading.Event
实例以确保提示线程在关闭之前关闭
继续。在特定方法的文档文本中查看更多详细信息:
from threading import Thread, Event
from queue import Queue, Empty
import time
SENTINEL = object()
class PromptManager(Thread):
def __init__(self, timeout):
super().__init__()
self.timeout = timeout
self._in_queue = Queue()
self._out_queue = Queue()
self.prompter = Thread(target=self._prompter, daemon=True)
self.start_time = None
self._prompter_exit = Event() # synchronization for shutdown
self._echoed = Event() # synchronization for terminal output
def run(self):
"""Run in worker-thread. Start prompt-thread, fetch passed
inputs from in_queue and check for timeout. Forward inputs for
`_poll` in parent. If timeout occurs, enqueue SENTINEL to
break the for-loop in `_poll()`.
"""
self.start_time = time.time()
self.prompter.start()
while self.time_left > 0:
try:
txt = self._in_queue.get(timeout=self.time_left)
except Empty:
self._out_queue.put(SENTINEL)
else:
self._out_queue.put(txt)
print("\nTime is out! Press ENTER to continue.")
self._prompter_exit.wait()
@property
def time_left(self):
return self.timeout - (time.time() - self.start_time)
def start(self):
"""Start manager-thread."""
super().start()
self._poll()
def _prompter(self):
"""Prompting target function for execution in prompter-thread."""
while self.time_left > 0:
self._in_queue.put(input('>$ '))
self._echoed.wait() # prevent intermixed display
self._echoed.clear()
self._prompter_exit.set()
def _poll(self):
"""Get forwarded inputs from the manager-thread executing `run()`
and process them in the parent-thread.
"""
for msg in iter(self._out_queue.get, SENTINEL):
print(f'you typed: {msg}')
self._echoed.set()
# finalize
self._echoed.set()
self._prompter_exit.wait()
self.join()
if __name__ == '__main__':
pm = PromptManager(timeout=5)
pm.start()
示例输出:
>$ Hello
you typed: Hello
>$ Wor
Time is out! Press ENTER to continue.
Process finished with exit code 0
请注意,在尝试输入“世界”时,此处会弹出超时消息。
答案 2 :(得分:1)
这是一个简短的方法,无需使用信号,注意:在用户输入内容然后检查条件之前,while循环将被阻止。
from datetime import datetime, timedelta
t = 5 # You can type for 5 seconds
def timeup():
final_time = datetime.now() + timedelta(seconds=t)
print("You can enter now for" + str(t) + " seconds")
while datetime.now() < final_time:
input()
print("STOP TYPING")
timeup()