Python 打印收到的消息,同时提示用户在聊天程序中输入
我在Python上创建了一个聊天应用程序,没有使用非标准库,在提示用户输入消息并发送消息时遇到了一个问题Python 打印收到的消息,同时提示用户在聊天程序中输入,python,python-3.x,multithreading,Python,Python 3.x,Multithreading,我在Python上创建了一个聊天应用程序,没有使用非标准库,在提示用户输入消息并发送消息时遇到了一个问题 def printit(): threading.Timer(5.0, printit).start() print("This is a test message!") def prompt(): while True: msg = input("Your Message: ") def main(): thread_prompt = t
def printit():
threading.Timer(5.0, printit).start()
print("This is a test message!")
def prompt():
while True:
msg = input("Your Message: ")
def main():
thread_prompt = threading.Thread(target = prompt)
thread_prompt.start()
printit()
虽然我希望收到的任何消息都显示在与提示符不同的行上,但此时发生的情况是这样的(例如,用户试图键入并发送“hello world”):
而我希望它是如下所示:
This is a test message!
Your Message: hello wor
这是否可以在不使用外部库的情况下实现?另外,我还没有实现发送消息的套接字/服务器,所以现在我使用
threading.Timer
来模拟每5秒发送一次的消息 我不认为您可以按照这个特定的顺序(测试消息后面跟着提示)轻松地完成您想要的事情,但是相反的顺序(提示后面跟着测试消息)是很容易实现的。不要打印测试消息,而是将其排队,然后在用户按Enter键时打印所有排队的消息
queue = []
lock = threading.Lock()
def printit():
threading.Timer(5.0, printit).start()
lock.acquire()
queue.append("This is a test message!")
lock.release()
def prompt():
global queue
while True:
msg = input("Your Message: ")
lock.acquire()
while queue:
print(queue.pop())
lock.release()
def main():
thread_prompt = threading.Thread(target = prompt)
thread_prompt.start()
printit()
queue = []
lock = threading.Lock()
def printit():
threading.Timer(5.0, printit).start()
lock.acquire()
queue.append("This is a test message!")
lock.release()
def prompt():
global queue
while True:
msg = input("Your Message: ")
lock.acquire()
while queue:
print(queue.pop())
lock.release()
def main():
thread_prompt = threading.Thread(target = prompt)
thread_prompt.start()
printit()