如何记录Python程序中用户输入对应的所有输出历史并支持回放
输入输出跟踪与回放实现方案
原代码仅记录用户输入,未关联对应输出,且递归逻辑存在冗余。以下是修改后的实现,可同时跟踪输入与对应输出,并支持最终回放:
# 存储(输入内容, 输出内容)的历史记录列表 history = [] def track_interaction(): global history answer = input("enter: ") # 根据输入匹配对应的输出内容 if answer == "off": output = "hi" elif answer == "forward": output = "moved forward" elif answer == "back": output = "moved back" else: output = "unknown command" # 处理未定义的输入 # 打印输出并记录到历史 print(output) history.append( (answer, output) ) # 输入不是"off"时继续接收下一个输入 if answer != "off": track_interaction() return history # 启动交互并获取完整历史 interaction_history = track_interaction() # 展示完整的输入输出历史 print("\n=== 交互历史 ===") for inp, out in interaction_history: print(f"输入: {inp} → 输出: {out}") # 执行输出回放 print("\n=== 回放输出 ===") for _, out in interaction_history: print(out)
关键修改说明:
- 将
history改为存储**(输入, 输出)**的元组列表,确保输入与输出一一对应 - 先统一确定
output变量,再执行打印和记录操作,避免重复代码 - 调整递归逻辑:只要输入不是
off就继续交互,逻辑更清晰 - 新增未知输入的处理,避免无输出的情况
- 内置历史展示和回放功能,直接满足"最终回放输出"的需求
内容的提问来源于stack exchange,提问作者ghost_gti
相关产品推荐
相关产品推荐

