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

如何为Python远程TCL命令行工具添加按键调用历史命令功能

实现Python命令行工具的历史命令回溯功能

你当前的Python工具通过input()获取TCL命令并发送到远程服务器,现在需要添加上下箭头按键访问历史命令的功能,替换原生input()的局限。

解决方案

Python原生input()不支持命令历史,我们可以用readline模块(Unix/Linux/macOS系统自带),Windows系统则需要安装pyreadline3替代。该模块能提供命令行历史、按键导航、搜索等功能。

步骤1:安装依赖(仅Windows需要)

在命令行执行:

pip install pyreadline3

步骤2:修改原有代码

核心改动点:

  • 引入兼容跨平台的readline模块
  • 维护命令历史并实现去重,避免重复存储相同命令
  • 用readline.readline()替代input(),自定义提示符
  • 修复原代码中list变量名覆盖内置类型的问题

修改后的完整代码:

import artistlib as a
# 跨平台引入readline模块
try:
    import readline
except ImportError:
    import pyreadline3 as readline

# 替换原list变量名,避免覆盖内置类型
response_types = ["SUCCESS", "RESULT", "STDOUT"]
command_history = []
# 用集合实现历史命令去重
history_set = set()

rc = a.Junction()
com = ""
c = 0

# 封装带历史功能的输入函数
def get_input(prompt):
    line = readline.readline(prompt)
    line = line.strip()
    if line:
        # 仅存储未出现过的命令
        if line not in history_set:
            command_history.append(line)
            history_set.add(line)
            readline.add_history(line)
    return line

while com != "exit":
    com = get_input("Command: ")
    if not com:
        continue  # 跳过空命令
    
    ver = a.Junction.send(rc, com, "*")

    for resp_type in response_types:
        typ = a.Junction.pick(rc, ver, resp_type)
        if "IMAGE" in ver and not "{}" in typ:
            name = input("Save Image as: ")
            a.Junction.image(rc, name)
            print("Image saved as ", name)
            
        if not "{}" in typ:
            if "not found" not in typ:
                print(typ)
            else:
                c += 1
        else:
            c += 1

    if c >= 3 and "BASE64" not in ver:
        print(ver)

    c = 0

# 可选:退出时保存历史到文件,下次启动可读取加载
# with open("command_history.txt", "w") as f:
#     f.write("\n".join(command_history))

使用说明

  • 按上箭头:回溯上一条执行过的命令
  • 按下箭头:切换到下一条历史命令
  • 按Ctrl+R:搜索历史命令(输入关键词即可匹配)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:25:22