Ma.*_*ala 5 python multithreading python-multithreading python-3.x
我正在使用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!')
Run Code Online (Sandbox Code Playgroud)
问题是,即使时间到了,代码仍然等待输入.我希望循环在时间用完时完全停止.我该怎么做呢?谢谢!
此解决方案与平台无关,并立即中断打字以通知现有超时。不必等到用户按 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()
Run Code Online (Sandbox Code Playgroud)
示例输出:
>$ Hello
you typed: Hello
>$ Wor
Time is out! Press ENTER to continue.
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
请注意,在尝试键入“World”时会弹出此处的超时消息。
| 归档时间: |
|
| 查看次数: |
508 次 |
| 最近记录: |