You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python的stdin.read()/input()具备类Bash的编辑与历史功能?

实现类Bash的Python标准输入编辑与历史记录功能

完全可以实现,Python标准库的readline模块(Windows环境需用pyreadline3替代)就能提供你需要的类Bash输入编辑和历史记录功能。

核心实现步骤

  • 导入readline模块(Windows环境先执行pip install pyreadline3)
  • 利用模块自带的功能,自动支持光标自由移动、文本编辑、上下键调取历史输入
  • 可选配置历史记录的保存与读取,实现跨会话的历史留存

示例代码

import readline
import sys

# 配置历史记录:最多保存1000条,退出时写入文件
readline.set_history_length(1000)
try:
    readline.read_history_file('.cli_tool_history')
except FileNotFoundError:
    pass

def run_cli():
    while True:
        try:
            # 用readline.readline()替代stdin.readline(),或直接用input()
            user_input = readline.readline(prompt='> ')
            if not user_input:
                continue
            user_input = user_input.strip()
            if user_input == 'exit':
                break
            
            # 这里替换为你的业务逻辑
            print(f"处理输入: {user_input}")
            
            # 将有效输入添加到历史记录
            readline.add_history(user_input)
        except KeyboardInterrupt:
            print("\n程序终止")
            break
        except Exception as e:
            print(f"错误: {str(e)}")
    
    # 退出前保存历史记录
    readline.write_history_file('.cli_tool_history')

if __name__ == '__main__':
    run_cli()

功能说明

  • 编辑操作:支持左右箭头移动光标、Home/End跳转首尾、Backspace/Delete删除字符,还兼容Ctrl+A(光标到开头)、Ctrl+E(光标到结尾)、Ctrl+K(删除光标后所有内容)等Bash常用快捷键
  • 历史记录:按下上下箭头可快速调取之前输入过的内容,配置历史文件后,重启工具也能保留之前的输入记录
  • 替代方案:如果习惯用input(),直接替换readline.readline(prompt='> ')为input('> ')即可,input()内部会自动调用readline模块的功能

内容的提问来源于stack exchange,提问作者user1479670

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:04:56