最近,我一直在考虑在python3
中创建一个聊天室。我一直在尝试使用线程同时接收/打印传入消息并接收输入,并试图弄清楚如何防止传入文本覆盖用户的输入并将其分成不同的行。这是我的意思的示例:
import threading
import time
import sys
def show_message(msg):
while True:
sys.stdout.write(msg + "\n")
sys.stdout.flush()
time.sleep(2)
t = threading.Thread(target=show_message, args=("Example Message",))
t.start()
while True:
msg = input("Your message>")
print(f"<You> {msg}")
运行此命令时,它会成功地通过线程一次又一次地打印出"Example Message"
,并且在按回车键并输出<You> [the message input]
时输入有效,但是由于覆盖而将输入分成多行,因为"Example Message"
中的一个。有什么方法可以防止这种情况的发生,并将输入行保持在终端的顶部或底部,而使传入消息不会到达该行并进行拆分/覆盖?
非常感谢!