在 python 中使用命令行解释按键输入

问题描述 投票:0回答:1

我想在 python 中构建一个命令行,以通过远程控制将 TCL 命令发送到服务器。到目前为止,我从 python

input
函数获得命令。现在我想增加通过按键访问以前命令的可能性。

import artistlib as a

list = ["SUCCESS", "RESULT", "STDOUT"]
commands = []

rc = a.Junction()

com = ""

c = 0

while com != "exit":
    com = input("Command: ")
    
    ver = a.Junction.send(rc, com, "*")

    for i in list:
        typ = a.Junction.pick(rc, ver, i)
        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 "not found" in typ:
                print(typ)
            else:
                c += 1
        else:
            c += 1

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

    c = 0

else:
    exit()

我怎样才能在上面的代码中实现这个功能?

python command-line command-line-arguments
1个回答
0
投票

使用 rlwrap

类 Unix shell 中的一个简单解决方案,可能只是使用

rlwrap
调用您的脚本,这可以轻松提供您想要的效果,而无需大惊小怪地在 Python 中实现它。例如,

rlwrap python3 myscript.py

您可能必须安装

rlwrap
(例如,
apt install -y rlwrap
在 debian/ubuntu 发行版上)

在 Python 中使用提示工具包

如果您想专门使用 Python 代码集成此功能,您可以考虑使用 prompt-toolkit

 的历史功能,它可以帮助您在 prompt-toolkit
 框架内做同样的事情。 (你需要安装 prompt-toolkit -- 
pip install prompt-toolkit

在这种方法中,您只需要从提示工具包创建一个

PromptSession

对象(
session
)并将
input
替换为
session.prompt

from prompt_toolkit import PromptSession session = PromptSession() # ... while com != "exit": com = session.prompt("Command: ") # ...
这将使您在同一会话中回忆以前的输入。如果您希望能够调用所有以前的命令,即使是在重新启动/重新启动等过程中,您也可以将历史记录保存到文件中。

from prompt_toolkit import PromptSession from prompt_toolkit.history import FileHistory session = PromptSession(history=FileHistory('~/.myhistory'))
    
© www.soinside.com 2019 - 2024. All rights reserved.