在输入提示中启用箭头键导航

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

简单的输入循环

while True:
    query = input('> ')
    results = get_results(query)
    print(results)

不允许我使用箭头键

  1. 在输入的文本中向后移动光标以更改某些内容
  2. 按向上箭头可获取过去输入的条目
  3. 按向下箭头向与 (2) 相反的方向移动

它只是打印所有转义码:

> my query^[[C^[[D^[[D^[[D^[[A^[[A^[[A

如何让它表现得像 REPL 或 shell 提示符?

python python-3.x command-prompt read-eval-print-loop
2个回答
4
投票

使用

cmd
模块创建一个 cmd 解释器类,如下所示。

import cmd

class CmdParse(cmd.Cmd):
    prompt = '> '
    commands = []
    def do_list(self, line):
        print(self.commands)
    def default(self, line):
        print(line[::])
        # Write your code here by handling the input entered
        self.commands.append(line)
    def do_exit(self, line):
        return True

if __name__ == '__main__':
    CmdParse().cmdloop()

附上尝试以下几个命令时该程序的输出:

mithilesh@mithilesh-desktop:~/playground/on_the_fly$ python cmds.py 
> 123
123
> 456
456
> list
['123', '456']
> exit
mithilesh@mithilesh-desktop:~/playground/on_the_fly$ 

有关更多信息,请参阅文档


0
投票

cmd
python 库没有什么花哨的。它还在内部调用
input
。启用箭头键和其他稍微高级的功能(例如自动完成)的是
readline
导入。

所以你需要做的就是:

import readline
a = input('>')
© www.soinside.com 2019 - 2024. All rights reserved.