Python双人聊天程序如何在等待输入时同步更新聊天消息?
问题解决方法
你遇到的问题本质是单线程串行执行的阻塞问题:input() 函数会卡住程序流程,只有你发完消息才会执行读文件刷新的代码,自然没法实时收到对方的消息。你已经导入了threading多线程模块,直接把收发逻辑拆成两个独立线程跑就行,修改后的代码如下:
import os import threading import time username = input("Enter a Username: ") # 初始化聊天文件 with open("chat.txt", "w") as file: file.truncate(0) os.system("cls") # 记录上一次读取的文件大小,用于判断是否有新消息 last_file_size = 0 # 线程运行标记 running = True def reading_thread(): global last_file_size while running: current_size = os.path.getsize("chat.txt") # 只有文件内容有更新时才刷新界面 if current_size != last_file_size: os.system("cls") with open("chat.txt", "r", encoding="utf-8") as f: for line in f: print(line, end="") last_file_size = current_size # 每隔1秒检查一次新消息,降低资源占用 time.sleep(1) def writing_thread(): global running while running: b = input("") # 输入exit可以退出程序 if b.strip().lower() == "exit": running = False break message = f"{username}: {b}\n" with open("chat.txt", "a", encoding="utf-8") as g: g.write(message) # 启动收消息的守护线程,主线程结束时会自动关闭 threading.Thread(target=reading_thread, daemon=True).start() # 主线程运行发消息逻辑 writing_thread()
注意事项
- 两个聊天用户需要在同一路径下启动程序,才能共享
chat.txt的内容完成通信 - 如果是Linux/macOS系统,把代码里的
os.system("cls")替换为os.system("clear")即可正常清屏 - 输入
exit即可正常关闭程序
内容的提问来源于stack exchange,提问作者mmm
相关产品推荐
相关产品推荐

