-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtext_input.py
64 lines (53 loc) · 1.8 KB
/
text_input.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 文本输入交互的功能
# 开启新线程持续监听输入,当有输入时,事件通知,并将其存入队列
import threading
from queue import Queue
from loguru import logger
import time
class TextInput(threading.Thread):
def __init__(self, event: threading.Event = None) -> None:
super().__init__()
# 该事件用于通知外部有新的文本输入
if event == None:
self.event = threading.Event()
else:
self.event = event
self.text_queue = Queue(maxsize=3)
self.exit_flag = True
self.show_text = ""
# 退出线程
def exit(self):
self.exit_flag = False
self.event.set()
# 绑定事件
def bind_event(self, event: threading.Event):
self.event = event
def run(self):
logger.info("文本输入线程启动")
while self.exit_flag:
try:
self.text = input(self.show_text).strip()
except UnicodeDecodeError:
print("[ERROR] Encoding error in input")
except KeyboardInterrupt:
break
if self.exit_flag == False:
break
# 如果收到了文本输入
if self.text:
self.text_queue.put_nowait(self.text)
self.event.set()
time.sleep(1)
logger.info("文本输入线程退出")
if __name__ == "__main__":
text_input = TextInput()
text_input.start()
while True:
text_input.event.wait()
text_input.event.clear()
while not text_input.text_queue.empty():
text = text_input.text_queue.get_nowait()
print("输入的文本:{}".format(text))
if text == "q" or text == "exit":
text_input.exit()
exit()